python / python/cpython

Duck-typing in `inspect.getfile`

オープン
#131,628 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Running inspect.getsource(numpy.random.random_sample) yields

File ~\.conda\envs\sage-dev\Lib\inspect.py:943, in getfile(object)
    941 if iscode(object):
    942     return object.co_filename
--> 943 raise TypeError('module, class, method, function, traceback, frame, or '
    944                 'code object was expected, got {}'.format(
    945                 type(object).__name__))

since the cython function is not correct recognized as a "true" function (i.e. it is not derived from FunctionType). But since a Cython function correct provides __code__, all the information is actually there to properly get the source file.

Refs: https://github.com/cython/cython/blob/030e3886fa094ecae6121f8ccacaf814956dca5c/docs/src/userguide/limitations.rst#L34

While it is quite possible to emulate the interface of functions in Cython's own function type, and recent Cython releases have seen several improvements here, the "inspect" module does not consider a Cython implemented function a "function", because it tests the object type explicitly instead of comparing an abstract interface or an abstract base class. This has a negative impact on code that uses inspect to inspect function objects, but would require a change to Python itself.

and

At the very least, the inspect module should use more duck-typing internally. For example, consider this code from "getfile":

    if ismethod(object):

        object = object.__func__

    if isfunction(object):

        object = object.__code__

    if istraceback(object):

        object = object.tb_frame

    if isframe(object):

        object = object.f_code

    if iscode(object):

        return object.co_filename

Originally posted by @jdemeyer in #74257

Linked PRs
  • gh-131632

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

inspect.getfile と、issue に示されている isfunction/iscode チェックから始めてください。code を公開するオブジェクトがどのように処理されるかを比較し、その後、作業を始める前にリンクされている PR gh-131632 を確認してください。報告された Cython 関数が、既存の inspect.getfile の動作を壊すことなくソースファイルを解決できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。