weakref confusion

M

Mathias Mamsch

Hi,

I have some confusion concerning the weakref module.
I am trying to save a weak reference to a bound member function of a class
instance for using it as a callback function. But I always get dead
references, when I try to create a reference to a bound member function. It
seems as if an instance of a class owns no reference to its memberfunctions,
so the the reference count is always zero. How can I come behind that?


If I do:
----------------
import weakref

class A:
def Test(data): print data

def MyTest (data): print data
AInst = A()

x = weakref.ref (AInst.Test) # x is a dead reference
y = weakref.ref (MyTest) # y is a working reference
f = AInst.Test
z = weakref.ref(f) # z works ...
del f # now z dies ....
----------------
 
J

Jeff Epler

Hi,

I have some confusion concerning the weakref module.

This is because the class dictionary holds a '<function Test>', but the
expression 'A.Test' returns an '<unbound method A.Test>'. You can
understand why this is the case by looking at what happens in a
subclass:
>>> class A: ... def m(): pass
>>> class B(A): pass
>>> A.m, B.m
>>> A.__dict__['m']
<function m at 0x813adfc>

just like bound methods on instances, unbound methods are created "on
demand", and are tied to the class that the attribute reference was
performed on.

Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top