cpython icon indicating copy to clipboard operation
cpython copied to clipboard

Weird `inspect.getsource` behavior with generators

Open MarkRotchell opened this issue 1 year ago • 3 comments

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

MarkRotchell avatar Jul 03 '24 13:07 MarkRotchell