Python method reference kills garbage collection?
Mark Hammond
mhammond at skippinet.com.au
Thu Feb 7 07:35:39 EST 2002
Troels Walsted Hansen wrote:
> Consider the following program. What is so special about references to the
> object's own methods that cause the object to never be garbage collected?
Just answered that.
> Is this a cyclic reference problem,
Yes. self.f is a bound method. A bound method has a reference to a
class and an instance. The instance in this case is 'self', so you have
a cycle.
If you really want to do this, store a reference to the unbound method. Eg:
>>> class A:
... def __init__(self):
... self.f = self.__class__.func
... def __del__(self):
... print "dieing"
... def func(self):
... print "func"
...
>>> a=A()
>>> a.f
<unbound method A.func>
>>> a.func
<bound method A.func of <__main__.A instance at 0x011C9E08>>
To create a bound method from the unbound method (generally as a temp,
just before calling it), use the new module:
>>> import new
>>> new.instancemethod(a.f, a, A)
<bound method A.func of <__main__.A instance at 0x011C9E08>>
And it will self-destruct OK:
>>> a=None
>>>
Ahh - but it didn't die! Oh yeah - the bound method we just created
will be stored in "_" (as this was entered interactively. So enter any
new expression to replace "_"
>>> 1
dieing
1
>>>
Yay :)
Mark.
More information about the Python-list
mailing list