weakref confusion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mathias Mamsch

    weakref confusion

    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 ....
    ----------------


  • Jeff Epler

    #2
    Re: weakref confusion

    On Wed, Feb 25, 2004 at 06:36:59PM +0100, Mathias Mamsch wrote:[color=blue]
    > Hi,
    >
    > I have some confusion concerning the weakref module.[/color]

    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:[color=blue][color=green][color=darkred]
    >>> class A:[/color][/color][/color]
    ... def m(): pass[color=blue][color=green][color=darkred]
    >>> class B(A): pass
    >>> A.m, B.m[/color][/color][/color]
    (<unbound method A.m>, <unbound method B.m>)[color=blue][color=green][color=darkred]
    >>> A.__dict__['m'][/color][/color][/color]
    <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

    Comment

    Working...