blob: cc7b494c913ce7ce5186f7550889fda745b19375 [file] [log] [blame]
Fred Drake41deb1e2001-02-01 05:27:45 +00001"""Weak reference support for Python.
2
3This module is an implementation of PEP 205:
4
5http://python.sourceforge.net/peps/pep-0205.html
6"""
7
8import UserDict
9
10from _weakref import \
11 getweakrefcount, \
12 getweakrefs, \
13 ref, \
14 proxy, \
15 ReferenceError, \
16 CallableProxyType, \
17 ProxyType, \
18 ReferenceType
19
20ProxyTypes = (ProxyType, CallableProxyType)
21
22
23def mapping(dict=None):
24 return WeakDictionary(dict)
25
26
27class WeakDictionary(UserDict.UserDict):
28
29 # We inherit the constructor without worrying about the input
30 # dictionary; since it uses our .update() method, we get the right
31 # checks (if the other dictionary is a WeakDictionary, objects are
32 # unwrapped on the way out, and we always wrap on the way in).
33
34 def __getitem__(self, key):
35 o = self.data.get(key)()
36 if o is None:
37 raise KeyError, key
38 else:
39 return o
40
41 def __repr__(self):
42 return "<WeakDictionary at %s>" % id(self)
43
44 def __setitem__(self, key, value):
45 def remove(o, data=self.data, key=key):
46 del data[key]
47 self.data[key] = ref(value, remove)
48
49 def copy(self):
50 new = WeakDictionary()
51 for key, ref in self.data.items():
52 o = ref()
53 if o is not None:
54 new[key] = o
55
56 def get(self, key, default):
57 try:
58 ref = self.data[key]
59 except KeyError:
60 return default
61 else:
62 o = ref()
63 if o is None:
64 # This should only happen
65 return default
66 else:
67 return o
68
69 def items(self):
Fred Drake312a5dc2001-02-02 15:13:24 +000070 L = []
71 for key, ref in self.data.items():
Fred Drake41deb1e2001-02-01 05:27:45 +000072 key, ref = L[i]
73 o = ref()
74 if o is not None:
Fred Drake312a5dc2001-02-02 15:13:24 +000075 L.append((key, o))
Fred Drake41deb1e2001-02-01 05:27:45 +000076 return L
77
78 def popitem(self):
79 while 1:
80 key, ref = self.data.popitem()
81 o = ref()
82 if o is not None:
83 return key, o
84
85 def setdefault(self, key, default):
86 try:
87 ref = self.data[key]
88 except KeyError:
89 def remove(o, data=self.data, key=key):
90 del data[key]
91 ref = ref(default, remove)
92 self.data[key] = ref
93 return default
94 else:
95 return ref()
96
97 def update(self, dict):
98 d = self.data
99 L = []
100 for key, o in dict.items():
101 def remove(o, data=d, key=key):
102 del data[key]
103 L.append(key, ref(o, remove))
104 for key, r in L:
105 d[key] = r
106
107 def values(self):
108 L = []
109 for ref in self.data.values():
110 o = ref()
111 if o is not None:
112 L.append(o)
113 return L
114
115
116# no longer needed
117del UserDict