1
"""Weak reference support for Python.
3
This module is an implementation of PEP 205:
5
http://python.sourceforge.net/peps/pep-0205.html
10
from _weakref import \
20
ProxyTypes = (ProxyType, CallableProxyType)
22
__all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
23
"WeakKeyDictionary", "ReferenceType", "ProxyType",
24
"CallableProxyType", "ProxyTypes", "WeakValueDictionary"]
26
class WeakValueDictionary(UserDict.UserDict):
28
# We inherit the constructor without worrying about the input
29
# dictionary; since it uses our .update() method, we get the right
30
# checks (if the other dictionary is a WeakValueDictionary,
31
# objects are unwrapped on the way out, and we always wrap on the
34
def __getitem__(self, key):
35
o = self.data.get(key)()
42
return "<WeakValueDictionary at %s>" % id(self)
44
def __setitem__(self, key, value):
45
def remove(o, data=self.data, key=key):
47
self.data[key] = ref(value, remove)
50
new = WeakValueDictionary()
51
for key, ref in self.data.items():
57
def get(self, key, default=None):
65
# This should only happen
72
for key, ref in self.data.items():
80
key, ref = self.data.popitem()
85
def setdefault(self, key, default):
89
def remove(o, data=self.data, key=key):
91
ref = ref(default, remove)
97
def update(self, dict):
100
for key, o in dict.items():
101
def remove(o, data=d, key=key):
103
L.append((key, ref(o, remove)))
109
for ref in self.data.values():
116
class WeakKeyDictionary(UserDict.UserDict):
118
def __init__(self, dict=None):
120
if dict is not None: self.update(dict)
121
def remove(k, data=self.data):
123
self._remove = remove
125
def __getitem__(self, key):
126
return self.data[ref(key)]
129
return "<WeakKeyDictionary at %s>" % id(self)
131
def __setitem__(self, key, value):
132
self.data[ref(key, self._remove)] = value
135
new = WeakKeyDictionary()
136
for key, value in self.data.items():
142
def get(self, key, default=None):
143
return self.data.get(ref(key),default)
145
def has_key(self, key):
146
return self.data.has_key(ref(key))
150
for key, value in self.data.items():
158
for ref in self.data.keys():
166
key, value = self.data.popitem()
171
def setdefault(self, key, default):
172
return self.data.setdefault(ref(key, self._remove),default)
174
def update(self, dict):
177
for key, value in dict.items():
178
L.append((ref(key, self._remove), value))