pythongenerator

Is the generator expression stored anywhere semantically intact?


If I set a generator

myra = (x + 100 for x in range(5))

and then later do something with it, like

for i in myra:
    print(i)

the generator has run its course, cannot be iterated over again, got that.

But is there a way, before, during, or after use, to interrogate the generator object so it returns the generating string, or something semantically equivalent? e.g.

>>> print_the_foundation(myra)
a + 100 for a in range(5)

Solution

  • You can get the code object produced from the generator expression.

    >>> import dis
    >>> myra = (x+100 for x in range(5))
    >>> dis.dis(myra.gi_code)
      1           0 RETURN_GENERATOR
                  2 POP_TOP
                  4 RESUME                   0
                  6 LOAD_FAST                0 (.0)
            >>    8 FOR_ITER                 9 (to 30)
                 12 STORE_FAST               1 (x)
                 14 LOAD_FAST                1 (x)
                 16 LOAD_CONST               0 (100)
                 18 BINARY_OP                0 (+)
                 22 YIELD_VALUE              1
                 24 RESUME                   1
                 26 POP_TOP
                 28 JUMP_BACKWARD           11 (to 8)
            >>   30 END_FOR
                 32 RETURN_CONST             1 (None)
            >>   34 CALL_INTRINSIC_1         3 (INTRINSIC_STOPITERATION_ERROR)
                 36 RERAISE                  1