weakref.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 _weakrefset import WeakSet, _IterationGuard
  18. from exceptions import ReferenceError
  19. ProxyTypes = (ProxyType, CallableProxyType)
  20. __all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
  21. "WeakKeyDictionary", "ReferenceError", "ReferenceType", "ProxyType",
  22. "CallableProxyType", "ProxyTypes", "WeakValueDictionary", 'WeakSet']
  23. class WeakValueDictionary(UserDict.UserDict):
  24. """Mapping class that references values weakly.
  25. Entries in the dictionary will be discarded when no strong
  26. reference to the value exists anymore
  27. """
  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
  32. # way in).
  33. def __init__(*args, **kw):
  34. if not args:
  35. raise TypeError("descriptor '__init__' of 'WeakValueDictionary' "
  36. "object needs an argument")
  37. self = args[0]
  38. args = args[1:]
  39. if len(args) > 1:
  40. raise TypeError('expected at most 1 arguments, got %d' % len(args))
  41. def remove(wr, selfref=ref(self)):
  42. self = selfref()
  43. if self is not None:
  44. if self._iterating:
  45. self._pending_removals.append(wr.key)
  46. else:
  47. del self.data[wr.key]
  48. self._remove = remove
  49. # A list of keys to be removed
  50. self._pending_removals = []
  51. self._iterating = set()
  52. UserDict.UserDict.__init__(self, *args, **kw)
  53. def _commit_removals(self):
  54. l = self._pending_removals
  55. d = self.data
  56. # We shouldn't encounter any KeyError, because this method should
  57. # always be called *before* mutating the dict.
  58. while l:
  59. del d[l.pop()]
  60. def __getitem__(self, key):
  61. o = self.data[key]()
  62. if o is None:
  63. raise KeyError, key
  64. else:
  65. return o
  66. def __delitem__(self, key):
  67. if self._pending_removals:
  68. self._commit_removals()
  69. del self.data[key]
  70. def __contains__(self, key):
  71. try:
  72. o = self.data[key]()
  73. except KeyError:
  74. return False
  75. return o is not None
  76. def has_key(self, key):
  77. try:
  78. o = self.data[key]()
  79. except KeyError:
  80. return False
  81. return o is not None
  82. def __repr__(self):
  83. return "<WeakValueDictionary at %s>" % id(self)
  84. def __setitem__(self, key, value):
  85. if self._pending_removals:
  86. self._commit_removals()
  87. self.data[key] = KeyedRef(value, self._remove, key)
  88. def clear(self):
  89. if self._pending_removals:
  90. self._commit_removals()
  91. self.data.clear()
  92. def copy(self):
  93. new = WeakValueDictionary()
  94. for key, wr in self.data.items():
  95. o = wr()
  96. if o is not None:
  97. new[key] = o
  98. return new
  99. __copy__ = copy
  100. def __deepcopy__(self, memo):
  101. from copy import deepcopy
  102. new = self.__class__()
  103. for key, wr in self.data.items():
  104. o = wr()
  105. if o is not None:
  106. new[deepcopy(key, memo)] = o
  107. return new
  108. def get(self, key, default=None):
  109. try:
  110. wr = self.data[key]
  111. except KeyError:
  112. return default
  113. else:
  114. o = wr()
  115. if o is None:
  116. # This should only happen
  117. return default
  118. else:
  119. return o
  120. def items(self):
  121. L = []
  122. for key, wr in self.data.items():
  123. o = wr()
  124. if o is not None:
  125. L.append((key, o))
  126. return L
  127. def iteritems(self):
  128. with _IterationGuard(self):
  129. for wr in self.data.itervalues():
  130. value = wr()
  131. if value is not None:
  132. yield wr.key, value
  133. def iterkeys(self):
  134. with _IterationGuard(self):
  135. for k in self.data.iterkeys():
  136. yield k
  137. __iter__ = iterkeys
  138. def itervaluerefs(self):
  139. """Return an iterator that yields the weak references to the values.
  140. The references are not guaranteed to be 'live' at the time
  141. they are used, so the result of calling the references needs
  142. to be checked before being used. This can be used to avoid
  143. creating references that will cause the garbage collector to
  144. keep the values around longer than needed.
  145. """
  146. with _IterationGuard(self):
  147. for wr in self.data.itervalues():
  148. yield wr
  149. def itervalues(self):
  150. with _IterationGuard(self):
  151. for wr in self.data.itervalues():
  152. obj = wr()
  153. if obj is not None:
  154. yield obj
  155. def popitem(self):
  156. if self._pending_removals:
  157. self._commit_removals()
  158. while 1:
  159. key, wr = self.data.popitem()
  160. o = wr()
  161. if o is not None:
  162. return key, o
  163. def pop(self, key, *args):
  164. if self._pending_removals:
  165. self._commit_removals()
  166. try:
  167. o = self.data.pop(key)()
  168. except KeyError:
  169. if args:
  170. return args[0]
  171. raise
  172. if o is None:
  173. raise KeyError, key
  174. else:
  175. return o
  176. def setdefault(self, key, default=None):
  177. try:
  178. wr = self.data[key]
  179. except KeyError:
  180. if self._pending_removals:
  181. self._commit_removals()
  182. self.data[key] = KeyedRef(default, self._remove, key)
  183. return default
  184. else:
  185. return wr()
  186. def update(*args, **kwargs):
  187. if not args:
  188. raise TypeError("descriptor 'update' of 'WeakValueDictionary' "
  189. "object needs an argument")
  190. self = args[0]
  191. args = args[1:]
  192. if len(args) > 1:
  193. raise TypeError('expected at most 1 arguments, got %d' % len(args))
  194. dict = args[0] if args else None
  195. if self._pending_removals:
  196. self._commit_removals()
  197. d = self.data
  198. if dict is not None:
  199. if not hasattr(dict, "items"):
  200. dict = type({})(dict)
  201. for key, o in dict.items():
  202. d[key] = KeyedRef(o, self._remove, key)
  203. if len(kwargs):
  204. self.update(kwargs)
  205. def valuerefs(self):
  206. """Return a list of weak references to the values.
  207. The references are not guaranteed to be 'live' at the time
  208. they are used, so the result of calling the references needs
  209. to be checked before being used. This can be used to avoid
  210. creating references that will cause the garbage collector to
  211. keep the values around longer than needed.
  212. """
  213. return self.data.values()
  214. def values(self):
  215. L = []
  216. for wr in self.data.values():
  217. o = wr()
  218. if o is not None:
  219. L.append(o)
  220. return L
  221. class KeyedRef(ref):
  222. """Specialized reference that includes a key corresponding to the value.
  223. This is used in the WeakValueDictionary to avoid having to create
  224. a function object for each key stored in the mapping. A shared
  225. callback object can use the 'key' attribute of a KeyedRef instead
  226. of getting a reference to the key from an enclosing scope.
  227. """
  228. __slots__ = "key",
  229. def __new__(type, ob, callback, key):
  230. self = ref.__new__(type, ob, callback)
  231. self.key = key
  232. return self
  233. def __init__(self, ob, callback, key):
  234. super(KeyedRef, self).__init__(ob, callback)
  235. class WeakKeyDictionary(UserDict.UserDict):
  236. """ Mapping class that references keys weakly.
  237. Entries in the dictionary will be discarded when there is no
  238. longer a strong reference to the key. This can be used to
  239. associate additional data with an object owned by other parts of
  240. an application without adding attributes to those objects. This
  241. can be especially useful with objects that override attribute
  242. accesses.
  243. """
  244. def __init__(self, dict=None):
  245. self.data = {}
  246. def remove(k, selfref=ref(self)):
  247. self = selfref()
  248. if self is not None:
  249. if self._iterating:
  250. self._pending_removals.append(k)
  251. else:
  252. del self.data[k]
  253. self._remove = remove
  254. # A list of dead weakrefs (keys to be removed)
  255. self._pending_removals = []
  256. self._iterating = set()
  257. if dict is not None:
  258. self.update(dict)
  259. def _commit_removals(self):
  260. # NOTE: We don't need to call this method before mutating the dict,
  261. # because a dead weakref never compares equal to a live weakref,
  262. # even if they happened to refer to equal objects.
  263. # However, it means keys may already have been removed.
  264. l = self._pending_removals
  265. d = self.data
  266. while l:
  267. try:
  268. del d[l.pop()]
  269. except KeyError:
  270. pass
  271. def __delitem__(self, key):
  272. del self.data[ref(key)]
  273. def __getitem__(self, key):
  274. return self.data[ref(key)]
  275. def __repr__(self):
  276. return "<WeakKeyDictionary at %s>" % id(self)
  277. def __setitem__(self, key, value):
  278. self.data[ref(key, self._remove)] = value
  279. def copy(self):
  280. new = WeakKeyDictionary()
  281. for key, value in self.data.items():
  282. o = key()
  283. if o is not None:
  284. new[o] = value
  285. return new
  286. __copy__ = copy
  287. def __deepcopy__(self, memo):
  288. from copy import deepcopy
  289. new = self.__class__()
  290. for key, value in self.data.items():
  291. o = key()
  292. if o is not None:
  293. new[o] = deepcopy(value, memo)
  294. return new
  295. def get(self, key, default=None):
  296. return self.data.get(ref(key),default)
  297. def has_key(self, key):
  298. try:
  299. wr = ref(key)
  300. except TypeError:
  301. return 0
  302. return wr in self.data
  303. def __contains__(self, key):
  304. try:
  305. wr = ref(key)
  306. except TypeError:
  307. return 0
  308. return wr in self.data
  309. def items(self):
  310. L = []
  311. for key, value in self.data.items():
  312. o = key()
  313. if o is not None:
  314. L.append((o, value))
  315. return L
  316. def iteritems(self):
  317. with _IterationGuard(self):
  318. for wr, value in self.data.iteritems():
  319. key = wr()
  320. if key is not None:
  321. yield key, value
  322. def iterkeyrefs(self):
  323. """Return an iterator that yields the weak references to the keys.
  324. The references are not guaranteed to be 'live' at the time
  325. they are used, so the result of calling the references needs
  326. to be checked before being used. This can be used to avoid
  327. creating references that will cause the garbage collector to
  328. keep the keys around longer than needed.
  329. """
  330. with _IterationGuard(self):
  331. for wr in self.data.iterkeys():
  332. yield wr
  333. def iterkeys(self):
  334. with _IterationGuard(self):
  335. for wr in self.data.iterkeys():
  336. obj = wr()
  337. if obj is not None:
  338. yield obj
  339. __iter__ = iterkeys
  340. def itervalues(self):
  341. with _IterationGuard(self):
  342. for value in self.data.itervalues():
  343. yield value
  344. def keyrefs(self):
  345. """Return a list of weak references to the keys.
  346. The references are not guaranteed to be 'live' at the time
  347. they are used, so the result of calling the references needs
  348. to be checked before being used. This can be used to avoid
  349. creating references that will cause the garbage collector to
  350. keep the keys around longer than needed.
  351. """
  352. return self.data.keys()
  353. def keys(self):
  354. L = []
  355. for wr in self.data.keys():
  356. o = wr()
  357. if o is not None:
  358. L.append(o)
  359. return L
  360. def popitem(self):
  361. while 1:
  362. key, value = self.data.popitem()
  363. o = key()
  364. if o is not None:
  365. return o, value
  366. def pop(self, key, *args):
  367. return self.data.pop(ref(key), *args)
  368. def setdefault(self, key, default=None):
  369. return self.data.setdefault(ref(key, self._remove),default)
  370. def update(self, dict=None, **kwargs):
  371. d = self.data
  372. if dict is not None:
  373. if not hasattr(dict, "items"):
  374. dict = type({})(dict)
  375. for key, value in dict.items():
  376. d[ref(key, self._remove)] = value
  377. if len(kwargs):
  378. self.update(kwargs)