Destruction of generator objects

Kay Schluehr kay.schluehr at gmx.net
Sat Aug 11 14:20:23 CEST 2007


On Aug 11, 2:00 pm, Stefan Bellon <sbel... at sbellon.de> wrote:
> On Sat, 11 Aug, Kay Schluehr wrote:
> > Honestly, I'd recommend wrapping the generator into a function object,
> > create the resource on construction ( or pass it ) and destroy it
> > implementing __del__.
>
> > def gen_value(self):
> >     while True:
> >         yield self.iter.next()
>
> > class GeneratorObj(object):
> >     def __init__(self, obj, gen):
> >         self.iter = make_iter(obj)
> >         self.gen  = gen(self)
>
> >     def __del__(self):
> >         destroy(self.iter)
>
> >     def next(self):
> >         return self.gen.next()
>
> Ok, I think there is an __iter__ missing in order to implement the
> iterator protocol, and I don't see why the generator cannot be inside
> the class itself.

Sure.

[...]

> But I do not see an output of "gen del" which makes me think that the
> destructor is not called, thus not releasing the resource. It seems I
> have not completely understood how generators work ...

But why shall the destructor be called? Your example does not indicate
that a ListGenerator object is somewhere destroyed neither explicitely
using del nor implicitely by destroying the scope it is living in.




More information about the Python-list mailing list