Skip to content

Instantly share code, notes, and snippets.

@sebastien
Created August 23, 2012 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastien/3437414 to your computer and use it in GitHub Desktop.
Save sebastien/3437414 to your computer and use it in GitHub Desktop.
Python WeakValueDict text
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