Reference Cycles with instance method

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 9 07:09:47 EST 2011


Amit Dev <amitdev at gmail.com> wrote:

> The object is not garbage collected, since there appears to be a cycle
> (between method m2 and A). I would expect this to behave the same as
> having another method "def m2(self): self.m1()", but unfortunately its
> not.
> In above case m2 seems to be in a.__dict__ which is causing the cycle.
> Any idea why this is so?
> 

Simply having a cycle will not prevent the object being collected unless 
you also have a __del__ method that you didn't show. If that is the issue 
perhaps you can refactor to remove __del__ (it is rarely needed in Python), 
or move it to another class.

m1 is an attribute of the class. It is a function (Python 3.x) or unbound 
method (Python 2.x). The difference is that m2 is an attribute of the 
instance and is bound to that instance.

When you use an instance to access a function that is defined in a class a 
new bound method object is created: this object contains a reference to the 
instance and inserts that as the first parameter whenever it is called.

So every time you call self.m1() a bound method is created and destroyed. 
If you save a reference to self.m1 without immediately calling it you have 
saved the bound method so that whenever you call it later it gets the 
correct 'self' parameter.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list