Reference Cycles with instance method

Amit Dev amitdev at gmail.com
Wed Mar 9 01:33:34 EST 2011


Simple question. If I have the following code:

class A:
    def __init__(self, s):
        self.s = s
        self.m2 = m1

    def m1(self):
        pass

if __name__ == '__main__':
    a = A("ads")
    a.m1()
    a = None

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?

Regards,
Amit



More information about the Python-list mailing list