import gc, traceback def gen(lst): try: try: yield 1 finally: print "finally 1" lst.append(1) yield 2 finally: print "finally 2" lst.append(2) # This works a = [] assert list(gen(a)) == [1, 2] assert a == [1, 2] # This does not b = [] x = gen(b) assert x.next() == 1 assert b == [] try: x.close() except RuntimeError: print "RuntimeError on close" # Python 2.5c1 says [1] here if b != [1, 2]: print 'b = %r, expecting [1, 2]' % (b,) del x gc.collect() assert b == [1, 2] # This doesn't get there at all c = [] x = gen(c) assert x.next() == 1 assert c == [] del x gc.collect() # RuntimeError ignored, but only the first finally executes if c != [1, 2]: print 'c = %r, expecting [1, 2]' % (c,)