[Python-Dev] Generator cleanup idea (patch: try/finally in generators)

Oren Tirosh oren-py-d@hishome.net
Tue, 30 Jul 2002 12:39:27 -0400


On Tue, Jul 30, 2002 at 12:24:05PM +0200, Matthias Urlichs wrote:
> def some_iter(foo):
> 	prepare(foo)
> 
> 	try:
> 		for i in foo:
> 			yield something(i)
> 	finally:
> 		cleanup(foo)
> 
> painlessly transmutes to this:
> 
> class some_iter(object):
> 	def __init__(foo):
> 		prepare(foo)
> 
> 		self.foo = foo
> 		self.it = foo.__iter__()
> 
> 	def next(self):
> 		i = self.it.next()
> 		return something(i)
> 
> 	def __del__(self):
> 		cleanup(self.foo)

Bad example.  Generators are useful precisely because some types of code
are quite painful to change to this form.

Anyway, it appears that generators can create reference loops if someone 
was peverted enough to keep a reference to the generator inside the 
generator.  It doesn't seem to be worth the effort of making generators 
into GC objects just for this.

	Oren