Vek.M1234 Vek.M1234 - 5 months ago 9
Python Question

GeneratorExit, close() does not cause a traceback/exception - how?

def receiver():
print("Ready to receive")
# try:
while True:
n = (yield)
print("Got %s" % n)
# except GeneratorExit:
# print("Receiver done")

r = receiver()
r.next()

r.send(10)

r.close()


When I comment out the
GeneratorExit
, the
close()
does not generate traceback! Why? However with the
except
active, i'm able to catch the
GeneratorExit
. How is that possible?

If
GeneratorExit
is an exception, then it should behave like all other exceptions and propagate out which it is doing - hence my ability to catch it using an
except
. But then surely without the
except
the parent python interpreter should catch the traceback like what happens with all other exceptions. What magic's going on here?

Answer

See generator.close() documentation.

It is stated that StopIteration and GeneratorExit exceptions are use internally to dictate how the generator exits, and thus are the only exceptions that are not propagated to the caller.

So if you want to re-raise a GeneratorExit exception, you probably have to catch it and encapsulate it in another custom exception.

Comments