Generator inside a class prevent __del__ ??

Terry Reedy tjreedy at udel.edu
Wed Apr 21 14:01:07 EDT 2004


"Emmanuel" <eastier at free.fr> wrote in message
news:40866ECD.A45758B9 at free.fr...
>
>
> Terry Reedy a écrit :
> > > >>> class toto:
> > >             def __init__(self):
> > >                 print "init"
> > >                 self.Coroutine = self.Gen()
> >
> > This creates a reference loop.  Delete this (and correct typo below)
and
> > 'problem' will disappear.

To amplify: the usual idiom for an instance-associated generator is to name
the generator function (method) __iter__ (with one param,  self) and to
create and get a reference to the generator via iter() or let the for loop
mechanism do so for you.

c = C(*args)
cgen =iter(c)

Then there is no reference loop.  And you can pass around the cgen object
just like any other.  If you only need the instance after initialization to
get the generator and you only need one generator for the instance, then
combine the two lines into

cgen = iter(C(*args))

and the *only* reference to the instance is the one in the generator, which
will disappear at the end of a for loop or with an explicit 'del cgen'.

There is also the question whether you actually *need* to get rid of the
object while the program is still running instead of just letting the
program finish and clean up.

Terry J. Reedy








More information about the Python-list mailing list