PageRenderTime 36ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/clion/bin/gdb/lib/python2.7/weakref.py

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