# they are called this instead of "ref" to avoid name collisions with
# the module-global ref() function imported from _weakref.
-import UserDict
+import collections
from _weakref import (
getweakrefcount,
"WeakSet"]
-class WeakValueDictionary(UserDict.UserDict):
+class WeakValueDictionary(collections.MutableMapping):
"""Mapping class that references values weakly.
Entries in the dictionary will be discarded when no strong
if self is not None:
del self.data[wr.key]
self._remove = remove
- UserDict.UserDict.__init__(self, *args, **kw)
+ self.data = d = {}
+ d.update(*args, **kw)
def __getitem__(self, key):
o = self.data[key]()
else:
return o
+ def __delitem__(self, key):
+ del self.data[key]
+
+ def __len__(self):
+ return sum(wr() is not None for wr in self.data.values())
+
def __contains__(self, key):
try:
o = self.data[key]()
L.append(o)
return L
+collections.MutableMapping.register(WeakValueDictionary)
class KeyedRef(ref):
"""Specialized reference that includes a key corresponding to the value.
super().__init__(ob, callback)
-class WeakKeyDictionary(UserDict.UserDict):
+class WeakKeyDictionary(collections.MutableMapping):
""" Mapping class that references keys weakly.
Entries in the dictionary will be discarded when there is no
def __getitem__(self, key):
return self.data[ref(key)]
+ def __len__(self):
+ return len(self.data)
+
def __repr__(self):
return "<WeakKeyDictionary at %s>" % id(self)
d[ref(key, self._remove)] = value
if len(kwargs):
self.update(kwargs)
+
+collections.MutableMapping.register(WeakKeyDictionary)