python / python/cpython

Misbehavior of `f.__code__.co_firstlineno` for decorated functions

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

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

interpreter-core topic-parser type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

See also: #139783

Compare:

dummy = lambda f: f                 # L1
@dummy                              # L2
def f():                            # L3
    return                          # L4
print(f.__code__.co_firstlineno)    # L5  # result = 2

with

dummy = lambda f: f                 # L1
pass                                # L2
def f():                            # L3
    return                          # L4
print(f.__code__.co_firstlineno)    # L5  # result = 3

and

dummy = lambda f: f                 # L1
@\
dummy                               # L3
def f():                            # L4
    return                          # L5
print(f.__code__.co_firstlineno)    # L6  # result = 3

In the last example, the line continuation after @ is not handled correctly and the first line for f.__code__ then becomes the line at dummy. Because of that, the values returned by inspect.findsource(f) will not be consistent and inspect.getsourcelines will not use the correct source (it will only start at "dummy" and will not contain the "@" part).

@serhiy-storchaka suggested that this is an issue in the AST parser. I however don't know how we should actually fix this.

Consequences to inspect.getsource and other introspection functions:
import inspect

def outer(*args, **kwargs):
    def inner(f):
        return f
    return deco

@(
    outer(
        ...
    )
)
def f():
    return "hello"

print(inspect.getsource(f))

On Python 3.12, the output is expected:

@(
    outer(
        ...
    )
)
def func():
    return "hello"

On Python 3.13.7, the output is missing the first line @(:

    outer(
        ...
    )
)
def func():
    return "hello"

On Python 3.13.9 and main, we are missing @ and outer parentheses:

    outer(
        ...
    )
CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

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

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

はじめの一歩

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

調査の方向性

3つのデコレータの例とネストされたデコレータの例を再現し、その後、inspect.findsource、inspect.getsourcelines、inspect.getsourceと併せてASTパーサーの動作を調査します。デコレートされた関数が、途中で継続するデコレータや開き括弧を含めて、正しい最初のソース行を報告し、イントロスペクションがデコレータのソース全体を返せば完了です。

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

評価

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

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

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