mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
Issue #14159: Fix the len() of weak containers (WeakSet, WeakKeyDictionary, WeakValueDictionary) to return a better approximation when some objects are dead or dying.
Moreover, the implementation is now O(1) rather than O(n). Thanks to Yury Selivanov for reporting.
This commit is contained in:
parent
eb977dac9c
commit
bbe2f60b3c
5 changed files with 115 additions and 3 deletions
|
@ -78,7 +78,7 @@ class WeakValueDictionary(collections.MutableMapping):
|
|||
del self.data[key]
|
||||
|
||||
def __len__(self):
|
||||
return sum(wr() is not None for wr in self.data.values())
|
||||
return len(self.data) - len(self._pending_removals)
|
||||
|
||||
def __contains__(self, key):
|
||||
try:
|
||||
|
@ -290,7 +290,7 @@ class WeakKeyDictionary(collections.MutableMapping):
|
|||
return self.data[ref(key)]
|
||||
|
||||
def __len__(self):
|
||||
return len(self.data)
|
||||
return len(self.data) - len(self._pending_removals)
|
||||
|
||||
def __repr__(self):
|
||||
return "<WeakKeyDictionary at %s>" % id(self)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue