Created
August 23, 2012 14:55
-
-
Save sebastien/3437414 to your computer and use it in GitHub Desktop.
Python WeakValueDict text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from weakref import WeakValueDictionary | |
class A(object): pass | |
# We want to make sure that the weak value dict loses keys | |
# that are not referenced anymore | |
d = WeakValueDictionary() | |
a = A() ; b = A() | |
d[id(a)] = a | |
d[id(b)] = b | |
# We have two items at first | |
print d.items() | |
assert len(d) == 2 | |
del a | |
# then only one, after deleting the reference to a | |
print d.items() | |
assert len(d) == 1 | |
del b | |
# then none, after deleting the reference to b | |
print d.items() | |
assert len(d) == 0 | |
# And now, will it work if we don't del? | |
def f(): | |
a = A() ; b = A() | |
d[id(a)] = a | |
d[id(b)] = b | |
assert len(d) == 2 | |
f() | |
print d.items() | |
assert len(d) == 0 | |
# EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment