Bruce Frederiksen schrieb:
I'm working on another project that uses generators a _lot_ and there are problems there because 'for' loops don't call 'close' on generators to clean things up. I've also hit problems where the code works fine on CPython, but fails on jython and ironpython because I'm relying on the reference counting to immediately collect abandoned generators and run their 'finally' clauses.
You can use "with closing" to ensure this. However, it bloats the code a tiny bit.
from __future__ import with_statement from itertools import islice from contextlib import closing
def gen(): try: print "before" yield 1 print "between" yield 2 print "after" except GeneratorExit: print "exit" finally: print "finally"
with closing(gen()) as g:
... for x in islice(g,1): ... print x ... before 1 exit finally