inspect.getsource returns unrelated code
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
The documentation of inspect.getsource states:
Return the text of the source code for an object. [...]
But the function returns slightly more code. It returns all lines of source code that overlap the object, even if the rest of the lines belong to different objects.
For example, the following code creates two lambdas in the same line, so inspect.getsource will return the code of both lambdas instead of just one.
import inspect
# Two function declarations in the same line
x = lambda: 1; y = lambda: 2
# prints "x = lambda: 1; y = lambda: 2\n"
print(repr(inspect.getsource(y)))
The returned code is not even necessarily valid Python, as the following list comprehension demonstrates:
import inspect
funcs = [
lambda: 1 for
_ in range(3)
]
# prints ' lambda: 1 for\n', including indentation and a stray "for"
print(repr(inspect.getsource(funcs[0])))
Background
I was trying to access the abstract syntax tree of a function (for JIT compilation), but that does not appear to be possible for lambdas.
Linked PRs
- gh-143301
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 inspect.getsource 開始,重現 issue 中的兩個範例,然後檢查周邊實作以及現有的原始碼擷取測試。釐清共用同一行或跨越推導式語法的 lambda 應有的行為,並加入回歸測試涵蓋範圍,以展示應該回傳什麼。一個關聯的 pull request gh-143301 表示相關工作已經移至其他地方。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- tooling
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100