Weird `inspect.getsource` behavior with generators
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 77.2k
- Fork
- 35.9k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug report
Bug description:
If you return two generators (one from a generator function and one a generator expression) from a function and use getsource on each, you get the code for the generator function for both.
def get_2_generators():
def my_generator_1():
for x in range(5):
yield x*2
my_generator_2 = (x*3 for x in range(6))
return my_generator_1(), my_generator_2
g1, g2 = get_2_generators()
getsource(g1.gi_code)
>>>' def my_generator_1():\n for x in range(5):\n yield x*2 \n'
getsource(g2.gi_code)
>>>' def my_generator_1():\n for x in range(5):\n yield x*2 \n'
Further, presumably not a bug but a current limitation, in general using getsource on generator-expression objects returns the code of the function they were created in, rather than the code of the generator expression itself, which can make things confusing when there are multiple such expressions, e.g.:
def get_2_generators():
my_generator_1 = (x*2 for x in range(5))
my_generator_2 = (x*3 for x in range(6))
return my_generator_1, my_generator_2
g1, g2 = get_2_generators()
getsource(g1.gi_code)
>>>'def get_2_generators():\n my_generator_1 = (x*2 for x in range(5)) \n my_generator_2 = (x*3 for x in range(6))\n return my_generator_1, my_generator_2\n'
getsource(g2.gi_code)
>>>'def get_2_generators():\n my_generator_1 = (x*2 for x in range(5)) \n my_generator_2 = (x*3 for x in range(6))\n return my_generator_1, my_generator_2\n'
Can we fix both of the above by making getsource return the code of the generator expression itself?
CPython versions tested on:
3.12
Operating systems tested on:
Windows
Linked PRs
- gh-121933
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con inspect.getsource e gli esempi di generator gi_code nel report, quindi esamina la PR collegata gh-121933 per conoscere la direzione attuale. Confronta i casi di funzioni generatore ed espressioni generatore e verifica che il lavoro completato distingua più generatori invece di restituire codice sorgente contenitore non correlato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- developer-experience
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 25/100