Misbehavior of `f.__code__.co_firstlineno` for decorated functions
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
重現三個 decorator 範例和巢狀 decorator 範例,然後搭配 inspect.findsource、inspect.getsourcelines 與 inspect.getsource 檢查 AST parser 的行為。完成的標準是:被裝飾的函式回報正確的第一行原始碼,包括跨行的 decorator 和左括號,且 introspection 回傳完整的 decorator 原始碼。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- compilers, devtools
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100