1

I want to create a WeakSet containing bound methods to be executed later:

class A(object):
    def f(self):
        print self.f, 'called'
a1 = A()
a2 = A()
a1.f()
a2.f()

This prints

<bound method A.f of <__main__.A object at 0x10533ffd0>> called
<bound method A.f of <__main__.A object at 0x105350990>> called

So far, so good. But now,

import weakref
ws = weakref.WeakSet()
ws.add(a1.f)
len(ws)

prints

0

Why?

A related question. Running in the python shell:

class A(object):
    def __del__(self):
        print '__del__(', self, ')'


a1 = A()
a1
<__main__.A object at 0x1053555d0>
del a1
a1

Traceback (most recent call last):
  File "<pyshell#124>", line 1, in <module>
    a1
NameError: name 'a1' is not defined

Why wasn't __del__called? Who's keeping a reference to a1?

Eduardo
  • 1,235
  • 16
  • 27
  • The first part is answered [here](http://stackoverflow.com/questions/599430/why-doesnt-the-weakref-work-on-this-bound-method?rq=1) – Eduardo Jan 15 '16 at 16:48
  • Answering the second part: `__del__` is not necessarily called when the reference counter gets to zero. Garbage collector may call it at any later point in time. – lvella Dec 30 '20 at 04:24

0 Answers0