mirror of
https://github.com/python/cpython.git
synced 2025-11-01 14:11:41 +00:00
Decouple weakref containers from UserDict
and teach them to use ABC instead. More work left to do later. Still need to modernize the API of the dictlike objects to more closely match regulars dicts.
This commit is contained in:
parent
93fa608626
commit
7ac609559d
1 changed files with 17 additions and 4 deletions
|
|
@ -9,7 +9,7 @@
|
|||
# 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,
|
||||
|
|
@ -30,7 +30,7 @@
|
|||
"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
|
||||
|
|
@ -48,7 +48,8 @@ def remove(wr, selfref=ref(self)):
|
|||
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]()
|
||||
|
|
@ -57,6 +58,12 @@ def __getitem__(self, 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]()
|
||||
|
|
@ -187,6 +194,7 @@ def values(self):
|
|||
L.append(o)
|
||||
return L
|
||||
|
||||
collections.MutableMapping.register(WeakValueDictionary)
|
||||
|
||||
class KeyedRef(ref):
|
||||
"""Specialized reference that includes a key corresponding to the value.
|
||||
|
|
@ -209,7 +217,7 @@ def __init__(self, ob, callback, key):
|
|||
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
|
||||
|
|
@ -235,6 +243,9 @@ def __delitem__(self, key):
|
|||
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)
|
||||
|
||||
|
|
@ -339,3 +350,5 @@ def update(self, dict=None, **kwargs):
|
|||
d[ref(key, self._remove)] = value
|
||||
if len(kwargs):
|
||||
self.update(kwargs)
|
||||
|
||||
collections.MutableMapping.register(WeakKeyDictionary)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue