David542 :
I have created the following generator function:
>>> def file_readlines(filepath):
... f = open(filepath, 'r')
... for line in f:
... yield line
...
>>> gen=file_readlines(filepath)
>>> next(gen)
When I examine the methods of the generator it shows the following:
...'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'`
throw
, send
, and close
are documented in Python Expressions, and I imagine code
and frame
are similar to a stacktrace object, but what are gi_running
and gi_yieldfrom
? How are those used?
Patrick Haugh :
gi_running
tells you whether or not the interpreter is currently executing instructions from the frame of the generator (gi_frame
)
gi_yieldfrom
is the iterator that the generator is yielding from. It was introduced in 3.5, and you can read the enhancement ticket here: https://bugs.python.org/issue24450
def yielder(gen):
yield from gen
x = range(5)
g = yielder(x)
print(g.gi_yieldfrom) # None
next(g) # delegate to the other iterator
print(g.gi_yieldfrom) # <range_iterator object at 0x0000026A0D72C830>
list(g) # exhaust iterator
print(g.gi_yieldfrom) # None