python / python/cpython

inspect.getsource returns unrelated code

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

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

docs
主要言語
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

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

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

はじめの一歩

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

調査の方向性

inspect.getsource から始めて、issue にある 2 つの例を再現します。次に、周辺の実装とソース抽出に関する既存のテストを調べます。同じ行を共有するラムダや、内包表記の構文にまたがるラムダについて、意図された動作を明確にし、何が返されるべきかを示す回帰テストのカバレッジを追加します。リンクされた pull request gh-143301 は、作業がすでに別の場所に移ったことを示しています。

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

評価

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

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

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