9
9
# they are called this instead of "ref" to avoid name collisions with
10
10
# the module-global ref() function imported from _weakref.
11
11
12
- import UserDict
12
+ import collections
13
13
14
14
from _weakref import (
15
15
getweakrefcount ,
30
30
"WeakSet" ]
31
31
32
32
33
- class WeakValueDictionary (UserDict . UserDict ):
33
+ class WeakValueDictionary (collections . MutableMapping ):
34
34
"""Mapping class that references values weakly.
35
35
36
36
Entries in the dictionary will be discarded when no strong
@@ -48,7 +48,8 @@ def remove(wr, selfref=ref(self)):
48
48
if self is not None :
49
49
del self .data [wr .key ]
50
50
self ._remove = remove
51
- UserDict .UserDict .__init__ (self , * args , ** kw )
51
+ self .data = d = {}
52
+ d .update (* args , ** kw )
52
53
53
54
def __getitem__ (self , key ):
54
55
o = self .data [key ]()
@@ -57,6 +58,12 @@ def __getitem__(self, key):
57
58
else :
58
59
return o
59
60
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
+
60
67
def __contains__ (self , key ):
61
68
try :
62
69
o = self .data [key ]()
@@ -187,6 +194,7 @@ def values(self):
187
194
L .append (o )
188
195
return L
189
196
197
+ collections .MutableMapping .register (WeakValueDictionary )
190
198
191
199
class KeyedRef (ref ):
192
200
"""Specialized reference that includes a key corresponding to the value.
@@ -209,7 +217,7 @@ def __init__(self, ob, callback, key):
209
217
super ().__init__ (ob , callback )
210
218
211
219
212
- class WeakKeyDictionary (UserDict . UserDict ):
220
+ class WeakKeyDictionary (collections . MutableMapping ):
213
221
""" Mapping class that references keys weakly.
214
222
215
223
Entries in the dictionary will be discarded when there is no
@@ -235,6 +243,9 @@ def __delitem__(self, key):
235
243
def __getitem__ (self , key ):
236
244
return self .data [ref (key )]
237
245
246
+ def __len__ (self ):
247
+ return len (self .data )
248
+
238
249
def __repr__ (self ):
239
250
return "<WeakKeyDictionary at %s>" % id (self )
240
251
@@ -339,3 +350,5 @@ def update(self, dict=None, **kwargs):
339
350
d [ref (key , self ._remove )] = value
340
351
if len (kwargs ):
341
352
self .update (kwargs )
353
+
354
+ collections .MutableMapping .register (WeakKeyDictionary )
0 commit comments