[Python-Dev] Anyone using weakrefs?

Tim Peters tim.one at home.com
Sat Mar 24 16:25:10 EST 2001


[Fred Drake]
> Is anyone out there playing with the weak references support yet?
> I'd *really* appreciate receiving a short snippet of non-contrived
> code that makes use of weak references to use in the documentation.

Alas, it's kinda like asking for a "short snippet" illustrating coroutines:
the need isn't apparent in tiny examples.

Still, I've been happily playing w/ this little module:

import weakref
id2obj_dict = weakref.mapping()

def remember(obj):
    id2obj_dict[id(obj)] = obj

def id2obj(id):
    return id2obj_dict.get(id, None)

In various introspective tools (like Cyclops.py), there's a need to keep
track of "other peoples'" class instances.  Before weakrefs, it was
impossible to do this without keeping the instances artificially alive.  Now
I can pass arbitrary instances to remember() above, then just use their ids
internally.  This doesn't keep the objects alive, but id2obj() above can
still get the objects back so long as they're still alive.

I suppose I could work with weakrefs directly instead of indirecting through
id()s, but most code of this nature I have is already mucking w/ ids anyway
(ints are small, fast, cheap and make great dict keys themselves).





More information about the Python-list mailing list