[Python-ideas] weakref.WeakKeyDictionary is (basically) useless

Antoine Pitrou solipsis at pitrou.net
Wed Dec 31 09:41:55 CET 2014


On Tue, 30 Dec 2014 19:22:36 -0500
Kevin Norris <nykevin.norris at gmail.com>
wrote:
> Let's talk about weakref.WeakKeyDictionary.
> 
> First, what is it?  It's a dictionary whose keys are referenced
> weakly.  That is, the dictionary takes weak references to its keys.
> If a key is garbage collected, it magically vanishes from the
> dictionary.  This saves programmers much of the trouble of manually
> culling dead weak references from data structures.
> 
> Why would you use it?  The official documentation mentions
> implementing a [descriptor][1].  See [this paste][2] for a simple
> example of this sort of thing.

How about something like this (untested):


import weakref

class Foo:
    def __init__(self):
        self._data = {}

    def __get__(self, obj, owner):
        _, val = self._data[id(obj)]
        return val

    def __set__(self, obj, value):
        key = id(obj)
        try:
            ref, _ = self._data[key]
        except KeyError:
            def on_destroy(_):
                del self._data[key]
            ref = weakref.ref(obj, on_destroy)
        self._data[key] = ref, value

    def __delete__(self, obj):
        del self._data[id(obj)]


class Bar:
    foo = Foo()


Regards

Antoine.




More information about the Python-ideas mailing list