Debian Codegraph @

lib-python/3/weakref.py

raw symbols SCIP
1 """Weak reference support for Python.
2
3 This module is an implementation of PEP 205:
4
5 https://peps.python.org/pep-0205/
6 """
7
8 # Naming convention: Variables named "wr" are weak reference objects;
9 # they are called this instead of "ref" to avoid name collisions with
10 # the module-global ref() function imported from _weakref.
11
12 from _weakref import (
13 getweakrefcount,
14 getweakrefs,
15 ref,
16 proxy,
17 CallableProxyType,
18 ProxyType,
19 ReferenceType,
20 _remove_dead_weakref)
21
22 from _weakrefset import WeakSet, _IterationGuard
23
24 import _collections_abc # Import after _weakref to avoid circular import.
25 import sys
26 import itertools
27
28 ProxyTypes = (ProxyType, CallableProxyType)
29
30 __all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
31 "WeakKeyDictionary", "ReferenceType", "ProxyType",
32 "CallableProxyType", "ProxyTypes", "WeakValueDictionary",
33 "WeakSet", "WeakMethod", "finalize"]
34
35
36 _collections_abc.MutableSet.register(WeakSet)
37
38 class WeakMethod(ref):
39 """
40 A custom `weakref.ref` subclass which simulates a weak reference to
41 a bound method, working around the lifetime problem of bound methods.
42 """
43
44 __slots__ = "_func_ref", "_meth_type", "_alive", "__weakref__"
45
46 def __new__(cls, meth, callback=None):
47 try:
48 obj = meth.__self__
49 func = meth.__func__
50 except AttributeError:
51 raise TypeError("argument should be a bound method, not {}"
52 .format(type(meth))) from None
53 def _cb(arg):
54 # The self-weakref trick is needed to avoid creating a reference
55 # cycle.
56 self = self_wr()
57 if self._alive:
58 self._alive = False
59 if callback is not None:
60 callback(self)
61 self = ref.__new__(cls, obj, _cb)
62 self._func_ref = ref(func, _cb)
63 self._meth_type = type(meth)
64 self._alive = True
65 self_wr = ref(self)
66 return self
67
68 def __call__(self):
69 obj = super().__call__()
70 func = self._func_ref()
71 if obj is None or func is None:
72 return None
73 return self._meth_type(func, obj)
74
75 def __eq__(self, other):
76 if isinstance(other, WeakMethod):
77 if not self._alive or not other._alive:
78 return self is other
79 return ref.__eq__(self, other) and self._func_ref == other._func_ref
80 return NotImplemented
81
82 def __ne__(self, other):
83 if isinstance(other, WeakMethod):
84 if not self._alive or not other._alive:
85 return self is not other
86 return ref.__ne__(self, other) or self._func_ref != other._func_ref
87 return NotImplemented
88
89 __hash__ = ref.__hash__
90
91
92 class WeakValueDictionary(_collections_abc.MutableMapping):
93 """Mapping class that references values weakly.
94
95 Entries in the dictionary will be discarded when no strong
96 reference to the value exists anymore
97 """
98 # We inherit the constructor without worrying about the input
99 # dictionary; since it uses our .update() method, we get the right
100 # checks (if the other dictionary is a WeakValueDictionary,
101 # objects are unwrapped on the way out, and we always wrap on the
102 # way in).
103
104 def __init__(self, other=(), /, **kw):
105 def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref):
106 self = selfref()
107 if self is not None:
108 if self._iterating:
109 self._pending_removals.append(wr.key)
110 else:
111 # Atomic removal is necessary since this function
112 # can be called asynchronously by the GC
113 _atomic_removal(self.data, wr.key)
114 self._remove = remove
115 # A list of keys to be removed
116 self._pending_removals = []
117 self._iterating = set()
118 self.data = {}
119 self.update(other, **kw)
120
121 def _commit_removals(self, _atomic_removal=_remove_dead_weakref):
122 pop = self._pending_removals.pop
123 d = self.data
124 # We shouldn't encounter any KeyError, because this method should
125 # always be called *before* mutating the dict.
126 while True:
127 try:
128 key = pop()
129 except IndexError:
130 return
131 _atomic_removal(d, key)
132
133 def __getitem__(self, key):
134 if self._pending_removals:
135 self._commit_removals()
136 o = self.data[key]()
137 if o is None:
138 raise KeyError(key)
139 else:
140 return o
141
142 def __delitem__(self, key):
143 if self._pending_removals:
144 self._commit_removals()
145 del self.data[key]
146
147 def __len__(self):
148 if self._pending_removals:
149 self._commit_removals()
150 # PyPy change: we can't rely on len(self.data) at all, because
151 # the weakref callbacks may be called at an unknown later time.
152 # original code was: return len(self.data)
153 result = 0
154 for wr in list(self.data.values()):
155 result += (wr() is not None)
156 return result
157
158 def __contains__(self, key):
159 if self._pending_removals:
160 self._commit_removals()
161 try:
162 o = self.data[key]()
163 except KeyError:
164 return False
165 return o is not None
166
167 def __repr__(self):
168 return "<%s at %#x>" % (self.__class__.__name__, id(self))
169
170 def __setitem__(self, key, value):
171 if self._pending_removals:
172 self._commit_removals()
173 self.data[key] = KeyedRef(value, self._remove, key)
174
175 def copy(self):
176 if self._pending_removals:
177 self._commit_removals()
178 new = WeakValueDictionary()
179 with _IterationGuard(self):
180 for key, wr in self.data.items():
181 o = wr()
182 if o is not None:
183 new[key] = o
184 return new
185
186 __copy__ = copy
187
188 def __deepcopy__(self, memo):
189 from copy import deepcopy
190 if self._pending_removals:
191 self._commit_removals()
192 new = self.__class__()
193 with _IterationGuard(self):
194 for key, wr in self.data.items():
195 o = wr()
196 if o is not None:
197 new[deepcopy(key, memo)] = o
198 return new
199
200 def get(self, key, default=None):
201 if self._pending_removals:
202 self._commit_removals()
203 try:
204 wr = self.data[key]
205 except KeyError:
206 return default
207 else:
208 o = wr()
209 if o is None:
210 # This should only happen
211 return default
212 else:
213 return o
214
215 def items(self):
216 if self._pending_removals:
217 self._commit_removals()
218 with _IterationGuard(self):
219 for k, wr in self.data.items():
220 v = wr()
221 if v is not None:
222 yield k, v
223
224 def keys(self):
225 if self._pending_removals:
226 self._commit_removals()
227 with _IterationGuard(self):
228 for k, wr in self.data.items():
229 if wr() is not None:
230 yield k
231
232 __iter__ = keys
233
234 def itervaluerefs(self):
235 """Return an iterator that yields the weak references to the values.
236
237 The references are not guaranteed to be 'live' at the time
238 they are used, so the result of calling the references needs
239 to be checked before being used. This can be used to avoid
240 creating references that will cause the garbage collector to
241 keep the values around longer than needed.
242
243 """
244 if self._pending_removals:
245 self._commit_removals()
246 with _IterationGuard(self):
247 yield from self.data.values()
248
249 def values(self):
250 if self._pending_removals:
251 self._commit_removals()
252 with _IterationGuard(self):
253 for wr in self.data.values():
254 obj = wr()
255 if obj is not None:
256 yield obj
257
258 def popitem(self):
259 if self._pending_removals:
260 self._commit_removals()
261 while True:
262 key, wr = self.data.popitem()
263 o = wr()
264 if o is not None:
265 return key, o
266
267 def pop(self, key, *args):
268 if self._pending_removals:
269 self._commit_removals()
270 try:
271 o = self.data.pop(key)()
272 except KeyError:
273 o = None
274 if o is None:
275 if args:
276 return args[0]
277 else:
278 raise KeyError(key)
279 else:
280 return o
281
282 def setdefault(self, key, default=None):
283 try:
284 o = self.data[key]()
285 except KeyError:
286 o = None
287 if o is None:
288 if self._pending_removals:
289 self._commit_removals()
290 self.data[key] = KeyedRef(default, self._remove, key)
291 return default
292 else:
293 return o
294
295 def update(self, other=None, /, **kwargs):
296 if self._pending_removals:
297 self._commit_removals()
298 d = self.data
299 if other is not None:
300 if not hasattr(other, "items"):
301 other = dict(other)
302 for key, o in other.items():
303 d[key] = KeyedRef(o, self._remove, key)
304 for key, o in kwargs.items():
305 d[key] = KeyedRef(o, self._remove, key)
306
307 def valuerefs(self):
308 """Return a list of weak references to the values.
309
310 The references are not guaranteed to be 'live' at the time
311 they are used, so the result of calling the references needs
312 to be checked before being used. This can be used to avoid
313 creating references that will cause the garbage collector to
314 keep the values around longer than needed.
315
316 """
317 if self._pending_removals:
318 self._commit_removals()
319 return list(self.data.values())
320
321 def __ior__(self, other):
322 self.update(other)
323 return self
324
325 def __or__(self, other):
326 if isinstance(other, _collections_abc.Mapping):
327 c = self.copy()
328 c.update(other)
329 return c
330 return NotImplemented
331
332 def __ror__(self, other):
333 if isinstance(other, _collections_abc.Mapping):
334 c = self.__class__()
335 c.update(other)
336 c.update(self)
337 return c
338 return NotImplemented
339
340
341 class KeyedRef(ref):
342 """Specialized reference that includes a key corresponding to the value.
343
344 This is used in the WeakValueDictionary to avoid having to create
345 a function object for each key stored in the mapping. A shared
346 callback object can use the 'key' attribute of a KeyedRef instead
347 of getting a reference to the key from an enclosing scope.
348
349 """
350
351 __slots__ = "key",
352
353 def __new__(type, ob, callback, key):
354 self = ref.__new__(type, ob, callback)
355 self.key = key
356 return self
357
358 def __init__(self, ob, callback, key):
359 super().__init__(ob, callback)
360
361
362 class WeakKeyDictionary(_collections_abc.MutableMapping):
363 """ Mapping class that references keys weakly.
364
365 Entries in the dictionary will be discarded when there is no
366 longer a strong reference to the key. This can be used to
367 associate additional data with an object owned by other parts of
368 an application without adding attributes to those objects. This
369 can be especially useful with objects that override attribute
370 accesses.
371 """
372
373 def __init__(self, dict=None):
374 self.data = {}
375 def remove(k, selfref=ref(self)):
376 self = selfref()
377 if self is not None:
378 if self._iterating:
379 self._pending_removals.append(k)
380 else:
381 try:
382 del self.data[k]
383 except KeyError:
384 pass
385 self._remove = remove
386 # A list of dead weakrefs (keys to be removed)
387 self._pending_removals = []
388 self._iterating = set()
389 self._dirty_len = False
390 if dict is not None:
391 self.update(dict)
392
393 def _commit_removals(self):
394 # NOTE: We don't need to call this method before mutating the dict,
395 # because a dead weakref never compares equal to a live weakref,
396 # even if they happened to refer to equal objects.
397 # However, it means keys may already have been removed.
398 pop = self._pending_removals.pop
399 d = self.data
400 while True:
401 try:
402 key = pop()
403 except IndexError:
404 return
405
406 try:
407 del d[key]
408 except KeyError:
409 pass
410
411 def _scrub_removals(self):
412 d = self.data
413 self._pending_removals = [k for k in self._pending_removals if k in d]
414 self._dirty_len = False
415
416 def __delitem__(self, key):
417 self._dirty_len = True
418 del self.data[ref(key)]
419
420 def __getitem__(self, key):
421 return self.data[ref(key)]
422
423 def __len__(self):
424 # PyPy change: we can't rely on len(self.data) at all, because
425 # the weakref callbacks may be called at an unknown later time.
426 # if self._dirty_len and self._pending_removals:
427 # # self._pending_removals may still contain keys which were
428 # # explicitly removed, we have to scrub them (see issue #21173).
429 # self._scrub_removals()
430 # return len(self.data) - len(self._pending_removals)
431 #
432 result = 0
433 for wr in list(self.data):
434 result += (wr() is not None)
435 return result
436
437 def __repr__(self):
438 return "<%s at %#x>" % (self.__class__.__name__, id(self))
439
440 def __setitem__(self, key, value):
441 self.data[ref(key, self._remove)] = value
442
443 def copy(self):
444 new = WeakKeyDictionary()
445 with _IterationGuard(self):
446 for key, value in self.data.items():
447 o = key()
448 if o is not None:
449 new[o] = value
450 return new
451
452 __copy__ = copy
453
454 def __deepcopy__(self, memo):
455 from copy import deepcopy
456 new = self.__class__()
457 with _IterationGuard(self):
458 for key, value in self.data.items():
459 o = key()
460 if o is not None:
461 new[o] = deepcopy(value, memo)
462 return new
463
464 def get(self, key, default=None):
465 return self.data.get(ref(key),default)
466
467 def __contains__(self, key):
468 try:
469 wr = ref(key)
470 except TypeError:
471 return False
472 return wr in self.data
473
474 def items(self):
475 with _IterationGuard(self):
476 for wr, value in self.data.items():
477 key = wr()
478 if key is not None:
479 yield key, value
480
481 def keys(self):
482 with _IterationGuard(self):
483 for wr in self.data:
484 obj = wr()
485 if obj is not None:
486 yield obj
487
488 __iter__ = keys
489
490 def values(self):
491 with _IterationGuard(self):
492 for wr, value in self.data.items():
493 if wr() is not None:
494 yield value
495
496 def keyrefs(self):
497 """Return a list of weak references to the keys.
498
499 The references are not guaranteed to be 'live' at the time
500 they are used, so the result of calling the references needs
501 to be checked before being used. This can be used to avoid
502 creating references that will cause the garbage collector to
503 keep the keys around longer than needed.
504
505 """
506 return list(self.data)
507
508 def popitem(self):
509 self._dirty_len = True
510 while True:
511 key, value = self.data.popitem()
512 o = key()
513 if o is not None:
514 return o, value
515
516 def pop(self, key, *args):
517 self._dirty_len = True
518 return self.data.pop(ref(key), *args)
519
520 def setdefault(self, key, default=None):
521 return self.data.setdefault(ref(key, self._remove),default)
522
523 def update(self, dict=None, /, **kwargs):
524 d = self.data
525 if dict is not None:
526 if not hasattr(dict, "items"):
527 dict = type({})(dict)
528 for key, value in dict.items():
529 d[ref(key, self._remove)] = value
530 if len(kwargs):
531 self.update(kwargs)
532
533 def __ior__(self, other):
534 self.update(other)
535 return self
536
537 def __or__(self, other):
538 if isinstance(other, _collections_abc.Mapping):
539 c = self.copy()
540 c.update(other)
541 return c
542 return NotImplemented
543
544 def __ror__(self, other):
545 if isinstance(other, _collections_abc.Mapping):
546 c = self.__class__()
547 c.update(other)
548 c.update(self)
549 return c
550 return NotImplemented
551
552
553 class finalize:
554 """Class for finalization of weakrefable objects
555
556 finalize(obj, func, *args, **kwargs) returns a callable finalizer
557 object which will be called when obj is garbage collected. The
558 first time the finalizer is called it evaluates func(*arg, **kwargs)
559 and returns the result. After this the finalizer is dead, and
560 calling it just returns None.
561
562 When the program exits any remaining finalizers for which the
563 atexit attribute is true will be run in reverse order of creation.
564 By default atexit is true.
565 """
566
567 # Finalizer objects don't have any state of their own. They are
568 # just used as keys to lookup _Info objects in the registry. This
569 # ensures that they cannot be part of a ref-cycle.
570
571 __slots__ = ()
572 _registry = {}
573 _shutdown = False
574 _index_iter = itertools.count()
575 _dirty = False
576 _registered_with_atexit = False
577
578 class _Info:
579 __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index")
580
581 def __init__(self, obj, func, /, *args, **kwargs):
582 if not self._registered_with_atexit:
583 # We may register the exit function more than once because
584 # of a thread race, but that is harmless
585 import atexit
586 atexit.register(self._exitfunc)
587 finalize._registered_with_atexit = True
588 info = self._Info()
589 info.weakref = ref(obj, self)
590 info.func = func
591 info.args = args
592 info.kwargs = kwargs or None
593 info.atexit = True
594 info.index = next(self._index_iter)
595 self._registry[self] = info
596 finalize._dirty = True
597
598 def __call__(self, _=None):
599 """If alive then mark as dead and return func(*args, **kwargs);
600 otherwise return None"""
601 info = self._registry.pop(self, None)
602 if info and not self._shutdown:
603 return info.func(*info.args, **(info.kwargs or {}))
604
605 def detach(self):
606 """If alive then mark as dead and return (obj, func, args, kwargs);
607 otherwise return None"""
608 info = self._registry.get(self)
609 obj = info and info.weakref()
610 if obj is not None and self._registry.pop(self, None):
611 return (obj, info.func, info.args, info.kwargs or {})
612
613 def peek(self):
614 """If alive then return (obj, func, args, kwargs);
615 otherwise return None"""
616 info = self._registry.get(self)
617 obj = info and info.weakref()
618 if obj is not None:
619 return (obj, info.func, info.args, info.kwargs or {})
620
621 @property
622 def alive(self):
623 """Whether finalizer is alive"""
624 return self in self._registry
625
626 @property
627 def atexit(self):
628 """Whether finalizer should be called at exit"""
629 info = self._registry.get(self)
630 return bool(info) and info.atexit
631
632 @atexit.setter
633 def atexit(self, value):
634 info = self._registry.get(self)
635 if info:
636 info.atexit = bool(value)
637
638 def __repr__(self):
639 info = self._registry.get(self)
640 obj = info and info.weakref()
641 if obj is None:
642 return '<%s object at %#x; dead>' % (type(self).__name__, id(self))
643 else:
644 return '<%s object at %#x; for %r at %#x>' % \
645 (type(self).__name__, id(self), type(obj).__name__, id(obj))
646
647 @classmethod
648 def _select_for_exit(cls):
649 # Return live finalizers marked for exit, oldest first
650 L = [(f,i) for (f,i) in cls._registry.items() if i.atexit]
651 L.sort(key=lambda item:item[1].index)
652 return [f for (f,i) in L]
653
654 @classmethod
655 def _exitfunc(cls):
656 # At shutdown invoke finalizers for which atexit is true.
657 # This is called once all other non-daemonic threads have been
658 # joined.
659 reenable_gc = False
660 try:
661 if cls._registry:
662 import gc
663 if gc.isenabled():
664 reenable_gc = True
665 gc.disable()
666 pending = None
667 while True:
668 if pending is None or finalize._dirty:
669 pending = cls._select_for_exit()
670 finalize._dirty = False
671 if not pending:
672 break
673 f = pending.pop()
674 try:
675 # gc is disabled, so (assuming no daemonic
676 # threads) the following is the only line in
677 # this function which might trigger creation
678 # of a new finalizer
679 f()
680 except Exception:
681 sys.excepthook(*sys.exc_info())
682 assert f not in cls._registry
683 finally:
684 # prevent any more finalizers from executing during shutdown
685 finalize._shutdown = True
686 if reenable_gc:
687 gc.enable()