This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mark.dickinson
Recipients mark.dickinson
Date 2013-04-06.12:54:56
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1365252897.75.0.384188042072.issue17643@psf.upfronthosting.co.za>
In-reply-to
Content
It would be nice to be able to access the callback of a weakref as an attribute on the weakref itself.  For example:

Python 3.4.0a0 (default:2bf154ca43c6+, Apr  6 2013, 13:31:29) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import weakref
>>> x = {1, 2, 3}
>>> ref = weakref.ref(x, lambda ref: print("done"))
>>> ref.__callback__
<function <lambda> at 0x1004f56d0>
>>> del x
done
>>> ref.__callback__  # Returns None

I encountered this while writing a tool to show graphs of Python objects and their references to each other:  I wanted to be able to annotate each edge of the graph.  For something like a function, it's easy to use introspection to compare the reference target with f.__code__, f.__annotations__, etc.  For a weakref, I couldn't find an easy way to retrieve the callback (or even determine whether there *was* a callback associated to the weakref).  One can do a "gc.get_referents" call and hope that if there's exactly one object returned it's the callback, but that won't work so well with weakref.ref subclasses.

Patch attached:  it has tests but no doc updates as yet.
History
Date User Action Args
2013-04-06 12:54:57mark.dickinsonsetrecipients: + mark.dickinson
2013-04-06 12:54:57mark.dickinsonsetmessageid: <1365252897.75.0.384188042072.issue17643@psf.upfronthosting.co.za>
2013-04-06 12:54:57mark.dickinsonlinkissue17643 messages
2013-04-06 12:54:57mark.dickinsoncreate