Generator inside a class prevent __del__ ??
Emmanuel
eastier at free.fr
Wed Apr 21 08:53:33 EDT 2004
Terry Reedy a écrit :
> "Emmanuel" <eastier at free.fr> wrote in message
> news:4085BA96.651D2E4A at free.fr...
> > I run across this problem, and couldn't find any solution (python 2.2.2)
> ...
> > Here, everything is normal...
> > But creating a generator :
>
> You both defined generator function and called it to create generator
> iterator.
Yes, I don't have all the generators vocabulary yet...
>
>
> >
> > Code :
> > ===========
> >
> > >>> 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.
>
> > def __del__(self):
> > print "del"
> > def Gen(self):
>
> If you do not really use self in the resulting iterator, define this
> outside of the class without self as a parameter, and problem will
> disappear.
I didn't use self in order to provide a simple example. In my real class, self
is used...
>
>
> > yield 1
> >
> > >>> a = toto()
>
> did you mean 'c = toto()'?
Yes, sorry for that...
>
>
> > init
> > >>> c = []
> > <--- Nothing there !!!
> > ==============
> >
> > I can't understand why the destructor is not called when a generator is
> > created, and what I should do to have a "correct" behavior.
>
> Either do not create reference loop or break it with del c.Coroutine.
>
> Terry J. Reedy
Thank you very much for your answer, but I'm still not sure I understand it.
If I understand your words right, creating self.Coroutine as an iterator on
the generator function will create a reference on self, so if I want to use a
generator in a class ( and I really want to ), I must delete explicitly the
iterator before I destroy the object.
Trouble is, I _would_ like not to care about the lifetime of the object, and I
don't know where it will be destroyed.
Should I encapsulate this object in another one, like this :
import toto
class TotoCapsule:
def __init__( self ):
self.toto = toto.toto()
def __del__(self):
del self.toto.Coroutine
self.toto = None
And use TotoCapsule ?
But it means I have to write a lot of more code to access toto's method.
Is there a pattern I missed to dea l with that ?
Thanks a lot,
Emmanuel
More information about the Python-list
mailing list