Misbehavior of `f.__code__.co_firstlineno` for decorated functions
还没有人认领这个 Issue。
- 主要语言
- 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
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
复现三个装饰器示例和嵌套装饰器示例,然后结合 inspect.findsource、inspect.getsourcelines 和 inspect.getsource 检查 AST 解析器的行为。完成的标准是:被装饰的函数报告正确的第一行源代码,包括跨行的装饰器和左括号,并且内省返回完整的装饰器源代码。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers, devtools
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100