Consider the following definition for a Python generator:
def gen(x):
print("-- BEGIN --")
y = x + 1
yield y
#-- 'tail' of the generator
z = y + 1
print("z = %d" % z)
print("-- END --")
return z
(I) If one uses this generator as in
g1 = gen(1)
print( next(g1) )
the output will be
-- BEGIN --
2
Another next(g1)
will produce
z = 3
-- END --
along with a StopIteration
exception.
(II) If one exhausts the g1
generator, e.g., via list
g1 = gen(1)
print("result =", list(g1) )
the output will be
-- BEGIN --
z = 3
-- END --
result = [2]
without any exception.
Questions:
- What happens to the "tail" of the generator in case (I)? When will it be executed, if ever?
- Why did the tail did not execute in case (I), but executed in case (II)?
- Is there a standard way to exhaust the generator in a single step, like what
list
operation does inlist(g1)
? - Is it possible to recover the final returned value,
z
, after exhaustion?