8000 Decouple weakref containers from UserDict · python/cpython@7ac6095 · GitHub
[go: up one dir, main page]

Skip to content 8000

Commit 7ac6095

Browse files
committed
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.
1 parent 93fa608 commit 7ac6095

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

Lib/weakref.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
# they are called this instead of "ref" to avoid name collisions with
1010
# the module-global ref() function imported from _weakref.
1111

12-
import UserDict
12+
import collections
1313

1414
from _weakref import (
1515
getweakrefcount,
@@ -30,7 +30,7 @@
3030
"WeakSet"]
3131

3232

33-
class WeakValueDictionary(UserDict.UserDict):
33+
class WeakValueDictionary(collections.MutableMapping):
3434
"""Mapping class that references values weakly.
3535
3636
Entries in the dictionary will be discarded when no strong
@@ -48,7 +48,8 @@ def remove(wr, selfref=ref(self)):
4848
if self is not None:
4949
del self.data[wr.key]
5050
self._remove = remove
51-
UserDict.UserDict.__init__(self, *args, **kw)
51+
self.data = d = {}
52+
d.update(*args, **kw)
5253

5354
def __getitem__(self, key):
5455
o = self.data[key]()
@@ -57,6 +58,12 @@ def __getitem__(self, key):
5758
else:
5859
return o
5960

61+
def __delitem__(self, key):
62+
del self.data[key]
63+
64+
def __len__(self):
65+
return sum(wr() is not None for wr in self.data.values())
66+
6067
def __contains__(self, key):
6168
try:
6269
o = self.data[key]()
@@ -187,6 +194,7 @@ def values(self):
187194
L.append(o)
188195
return L
189196

197+
collections.MutableMapping.register(WeakValueDictionary)
190198

191199
class KeyedRef(ref):
192200
"""Specialized reference that includes a key corresponding to the value.
@@ -209,7 +217,7 @@ def __init__(self, ob, callback, key):
209217
super().__init__(ob, callback)
210218

211219

212-
class WeakKeyDictionary(UserDict.UserDict):
220+
class WeakKeyDictionary(collections.MutableMapping):
213221
""" Mapping class that references keys weakly.
214222
215223
Entries in the dictionary will be discarded when there is no
@@ -235,6 +243,9 @@ def __delitem__(self, key):
235243
def __getitem__(self, key):
236244
return self.data[ref(key)]
237245

246+
def __len__(self):
247+
return len(self.data)
248+
238249
def __repr__(self):
239250
return "<WeakKeyDictionary at %s>" % id(self)
240251

@@ -339,3 +350,5 @@ def update(self, dict=None, **kwargs):
339350
d[ref(key, self._remove)] = value
340351
if len(kwargs):
341352
self.update(kwargs)
353+
354+
collections.MutableMapping.register(WeakKeyDictionary)

0 commit comments

Comments
 (0)
0