/Lib/weakref.py

http://unladen-swallow.googlecode.com/ · Python · 355 lines · 311 code · 22 blank · 22 comment · 18 complexity · 35c7f84f1337f68075edb6673ce04d82 MD5 · raw file

  1. """Weak reference support for Python.
  2. This module is an implementation of PEP 205:
  3. http://www.python.org/dev/peps/pep-0205/
  4. """
  5. # Naming convention: Variables named "wr" are weak reference objects;
  6. # they are called this instead of "ref" to avoid name collisions with
  7. # the module-global ref() function imported from _weakref.
  8. import UserDict
  9. from _weakref import (
  10. getweakrefcount,
  11. getweakrefs,
  12. ref,
  13. proxy,
  14. CallableProxyType,
  15. ProxyType,
  16. ReferenceType)
  17. from exceptions import ReferenceError
  18. ProxyTypes = (ProxyType, CallableProxyType)
  19. __all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
  20. "WeakKeyDictionary", "ReferenceError", "ReferenceType", "ProxyType",
  21. "CallableProxyType", "ProxyTypes", "WeakValueDictionary"]
  22. class WeakValueDictionary(UserDict.UserDict):
  23. """Mapping class that references values weakly.
  24. Entries in the dictionary will be discarded when no strong
  25. reference to the value exists anymore
  26. """
  27. # We inherit the constructor without worrying about the input
  28. # dictionary; since it uses our .update() method, we get the right
  29. # checks (if the other dictionary is a WeakValueDictionary,
  30. # objects are unwrapped on the way out, and we always wrap on the
  31. # way in).
  32. def __init__(self, *args, **kw):
  33. def remove(wr, selfref=ref(self)):
  34. self = selfref()
  35. if self is not None:
  36. del self.data[wr.key]
  37. self._remove = remove
  38. UserDict.UserDict.__init__(self, *args, **kw)
  39. def __getitem__(self, key):
  40. o = self.data[key]()
  41. if o is None:
  42. raise KeyError, key
  43. else:
  44. return o
  45. def __contains__(self, key):
  46. try:
  47. o = self.data[key]()
  48. except KeyError:
  49. return False
  50. return o is not None
  51. def has_key(self, key):
  52. try:
  53. o = self.data[key]()
  54. except KeyError:
  55. return False
  56. return o is not None
  57. def __repr__(self):
  58. return "<WeakValueDictionary at %s>" % id(self)
  59. def __setitem__(self, key, value):
  60. self.data[key] = KeyedRef(value, self._remove, key)
  61. def copy(self):
  62. new = WeakValueDictionary()
  63. for key, wr in self.data.items():
  64. o = wr()
  65. if o is not None:
  66. new[key] = o
  67. return new
  68. def get(self, key, default=None):
  69. try:
  70. wr = self.data[key]
  71. except KeyError:
  72. return default
  73. else:
  74. o = wr()
  75. if o is None:
  76. # This should only happen
  77. return default
  78. else:
  79. return o
  80. def items(self):
  81. L = []
  82. for key, wr in self.data.items():
  83. o = wr()
  84. if o is not None:
  85. L.append((key, o))
  86. return L
  87. def iteritems(self):
  88. for wr in self.data.itervalues():
  89. value = wr()
  90. if value is not None:
  91. yield wr.key, value
  92. def iterkeys(self):
  93. return self.data.iterkeys()
  94. def __iter__(self):
  95. return self.data.iterkeys()
  96. def itervaluerefs(self):
  97. """Return an iterator that yields the weak references to the values.
  98. The references are not guaranteed to be 'live' at the time
  99. they are used, so the result of calling the references needs
  100. to be checked before being used. This can be used to avoid
  101. creating references that will cause the garbage collector to
  102. keep the values around longer than needed.
  103. """
  104. return self.data.itervalues()
  105. def itervalues(self):
  106. for wr in self.data.itervalues():
  107. obj = wr()
  108. if obj is not None:
  109. yield obj
  110. def popitem(self):
  111. while 1:
  112. key, wr = self.data.popitem()
  113. o = wr()
  114. if o is not None:
  115. return key, o
  116. def pop(self, key, *args):
  117. try:
  118. o = self.data.pop(key)()
  119. except KeyError:
  120. if args:
  121. return args[0]
  122. raise
  123. if o is None:
  124. raise KeyError, key
  125. else:
  126. return o
  127. def setdefault(self, key, default=None):
  128. try:
  129. wr = self.data[key]
  130. except KeyError:
  131. self.data[key] = KeyedRef(default, self._remove, key)
  132. return default
  133. else:
  134. return wr()
  135. def update(self, dict=None, **kwargs):
  136. d = self.data
  137. if dict is not None:
  138. if not hasattr(dict, "items"):
  139. dict = type({})(dict)
  140. for key, o in dict.items():
  141. d[key] = KeyedRef(o, self._remove, key)
  142. if len(kwargs):
  143. self.update(kwargs)
  144. def valuerefs(self):
  145. """Return a list of weak references to the values.
  146. The references are not guaranteed to be 'live' at the time
  147. they are used, so the result of calling the references needs
  148. to be checked before being used. This can be used to avoid
  149. creating references that will cause the garbage collector to
  150. keep the values around longer than needed.
  151. """
  152. return self.data.values()
  153. def values(self):
  154. L = []
  155. for wr in self.data.values():
  156. o = wr()
  157. if o is not None:
  158. L.append(o)
  159. return L
  160. class KeyedRef(ref):
  161. """Specialized reference that includes a key corresponding to the value.
  162. This is used in the WeakValueDictionary to avoid having to create
  163. a function object for each key stored in the mapping. A shared
  164. callback object can use the 'key' attribute of a KeyedRef instead
  165. of getting a reference to the key from an enclosing scope.
  166. """
  167. __slots__ = "key",
  168. def __new__(type, ob, callback, key):
  169. self = ref.__new__(type, ob, callback)
  170. self.key = key
  171. return self
  172. def __init__(self, ob, callback, key):
  173. super(KeyedRef, self).__init__(ob, callback)
  174. class WeakKeyDictionary(UserDict.UserDict):
  175. """ Mapping class that references keys weakly.
  176. Entries in the dictionary will be discarded when there is no
  177. longer a strong reference to the key. This can be used to
  178. associate additional data with an object owned by other parts of
  179. an application without adding attributes to those objects. This
  180. can be especially useful with objects that override attribute
  181. accesses.
  182. """
  183. def __init__(self, dict=None):
  184. self.data = {}
  185. def remove(k, selfref=ref(self)):
  186. self = selfref()
  187. if self is not None:
  188. del self.data[k]
  189. self._remove = remove
  190. if dict is not None: self.update(dict)
  191. def __delitem__(self, key):
  192. del self.data[ref(key)]
  193. def __getitem__(self, key):
  194. return self.data[ref(key)]
  195. def __repr__(self):
  196. return "<WeakKeyDictionary at %s>" % id(self)
  197. def __setitem__(self, key, value):
  198. self.data[ref(key, self._remove)] = value
  199. def copy(self):
  200. new = WeakKeyDictionary()
  201. for key, value in self.data.items():
  202. o = key()
  203. if o is not None:
  204. new[o] = value
  205. return new
  206. def get(self, key, default=None):
  207. return self.data.get(ref(key),default)
  208. def has_key(self, key):
  209. try:
  210. wr = ref(key)
  211. except TypeError:
  212. return 0
  213. return wr in self.data
  214. def __contains__(self, key):
  215. try:
  216. wr = ref(key)
  217. except TypeError:
  218. return 0
  219. return wr in self.data
  220. def items(self):
  221. L = []
  222. for key, value in self.data.items():
  223. o = key()
  224. if o is not None:
  225. L.append((o, value))
  226. return L
  227. def iteritems(self):
  228. for wr, value in self.data.iteritems():
  229. key = wr()
  230. if key is not None:
  231. yield key, value
  232. def iterkeyrefs(self):
  233. """Return an iterator that yields the weak references to the keys.
  234. The references are not guaranteed to be 'live' at the time
  235. they are used, so the result of calling the references needs
  236. to be checked before being used. This can be used to avoid
  237. creating references that will cause the garbage collector to
  238. keep the keys around longer than needed.
  239. """
  240. return self.data.iterkeys()
  241. def iterkeys(self):
  242. for wr in self.data.iterkeys():
  243. obj = wr()
  244. if obj is not None:
  245. yield obj
  246. def __iter__(self):
  247. return self.iterkeys()
  248. def itervalues(self):
  249. return self.data.itervalues()
  250. def keyrefs(self):
  251. """Return a list of weak references to the keys.
  252. The references are not guaranteed to be 'live' at the time
  253. they are used, so the result of calling the references needs
  254. to be checked before being used. This can be used to avoid
  255. creating references that will cause the garbage collector to
  256. keep the keys around longer than needed.
  257. """
  258. return self.data.keys()
  259. def keys(self):
  260. L = []
  261. for wr in self.data.keys():
  262. o = wr()
  263. if o is not None:
  264. L.append(o)
  265. return L
  266. def popitem(self):
  267. while 1:
  268. key, value = self.data.popitem()
  269. o = key()
  270. if o is not None:
  271. return o, value
  272. def pop(self, key, *args):
  273. return self.data.pop(ref(key), *args)
  274. def setdefault(self, key, default=None):
  275. return self.data.setdefault(ref(key, self._remove),default)
  276. def update(self, dict=None, **kwargs):
  277. d = self.data
  278. if dict is not None:
  279. if not hasattr(dict, "items"):
  280. dict = type({})(dict)
  281. for key, value in dict.items():
  282. d[ref(key, self._remove)] = value
  283. if len(kwargs):
  284. self.update(kwargs)