def demo(): from gc import (set_debug, DEBUG_LEAK, collect) collect() set_debug(DEBUG_LEAK) for test in (throw_leaks, close_leaks, del_leaks, next_okay, send_okay): print("Testing", test.__name__) g = leaky_generator() next(g) # Generator is now at the "yield" line print(g.gi_frame, "line", g.gi_frame.f_lineno) test(g) del g print("Leak count:", collect()) def leaky_generator(): try: raise Exception() except: # Exception handler with anonymous exception variable yield # Yield from exception handler def throw_leaks(g): try: g.throw(Exception()) except Exception: pass def close_leaks(g): g.close() def del_leaks(g): pass def next_okay(g): try: next(g) except StopIteration: pass def send_okay(g): try: g.send(None) except StopIteration: pass if __name__ == "__main__": demo()