Nick Coghlan wrote:
from contextlib import closing
with closing(itr): # Use the iterator in here as you wish # secure in the knowledge it will be # cleaned up promptly when you are done # whether it is a file, a generator or # something with a database connection for item in itr: print item
I seem to remember we've been here before. I'll be disappointed if I have to wrap every for-loop that I write in a with-statement on the offchance that it might be using a generator that needs finalisation in order to avoid leaking memory.
I'm becoming more and more convinced that we desperately need something better than __del__ methods to do finalisation. A garbage collector that can't be relied upon to collect garbage is simply not acceptable.