summaryrefslogtreecommitdiff
path: root/Lib/weakref.py
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2012-03-01 16:26:35 +0100
committerAntoine Pitrou <solipsis@pitrou.net>2012-03-01 16:26:35 +0100
commitbbe2f60b3c19ecaa02ca07be14474eaacfcb59a0 (patch)
tree768a0d9c5d1402c0d91dcaf9597e83adea6d892a /Lib/weakref.py
parenteb977dac9cfd590982d08d1a9f7bae58498648ca (diff)
downloadcpython-git-bbe2f60b3c19ecaa02ca07be14474eaacfcb59a0.tar.gz
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.
Diffstat (limited to 'Lib/weakref.py')
-rw-r--r--Lib/weakref.py4
1 files changed, 2 insertions, 2 deletions
diff --git a/Lib/weakref.py b/Lib/weakref.py
index 468f8f1029..fcb6b74d1b 100644
--- a/Lib/weakref.py
+++ b/Lib/weakref.py
@@ -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)