python / python/cpython

inspect.getsource returns unrelated code

Aperta
#143,299 8 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

docs
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia da inspect.getsource e riproduci i due esempi dell’issue. Poi esamina l’implementazione circostante e i test esistenti per l’estrazione del codice sorgente. Chiarisci il comportamento previsto per le lambda che condividono una riga o che si estendono su una sintassi di comprensione, e aggiungi una copertura di regressione che mostri cosa dovrebbe essere restituito. Una pull request collegata, gh-143301, indica che il lavoro è già stato spostato altrove.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.