|
| 1 | +""" |
| 2 | +Partial backport of Python 3.5's weakref module: |
| 3 | +
|
| 4 | + finalize (new in Python 3.4) |
| 5 | +
|
| 6 | +Backport modifications are marked with marked with "XXX backport". |
| 7 | +""" |
| 8 | +from __future__ import absolute_import |
| 9 | + |
| 10 | +import itertools |
| 11 | +import sys |
| 12 | +from weakref import ref |
| 13 | + |
| 14 | +__all__ = ['finalize'] |
| 15 | + |
| 16 | + |
| 17 | +class finalize(object): |
| 18 | + """Class for finalization of weakrefable objects |
| 19 | +
|
| 20 | + finalize(obj, func, *args, **kwargs) returns a callable finalizer |
| 21 | + object which will be called when obj is garbage collected. The |
| 22 | + first time the finalizer is called it evaluates func(*arg, **kwargs) |
| 23 | + and returns the result. After this the finalizer is dead, and |
| 24 | + calling it just returns None. |
| 25 | +
|
| 26 | + When the program exits any remaining finalizers for which the |
| 27 | + atexit attribute is true will be run in reverse order of creation. |
| 28 | + By default atexit is true. |
| 29 | + """ |
| 30 | + |
| 31 | + # Finalizer objects don't have any state of their own. They are |
| 32 | + # just used as keys to lookup _Info objects in the registry. This |
| 33 | + # ensures that they cannot be part of a ref-cycle. |
| 34 | + |
| 35 | + __slots__ = () |
| 36 | + _registry = {} |
| 37 | + _shutdown = False |
| 38 | + _index_iter = itertools.count() |
| 39 | + _dirty = False |
| 40 | + _registered_with_atexit = False |
| 41 | + |
| 42 | + class _Info(object): |
| 43 | + __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index") |
| 44 | + |
| 45 | + def __init__(self, obj, func, *args, **kwargs): |
| 46 | + if not self._registered_with_atexit: |
| 47 | + # We may register the exit function more than once because |
| 48 | + # of a thread race, but that is harmless |
| 49 | + import atexit |
| 50 | + atexit.register(self._exitfunc) |
| 51 | + finalize._registered_with_atexit = True |
| 52 | + info = self._Info() |
| 53 | + info.weakref = ref(obj, self) |
| 54 | + info.func = func |
| 55 | + info.args = args |
| 56 | + info.kwargs = kwargs or None |
| 57 | + info.atexit = True |
| 58 | + info.index = next(self._index_iter) |
| 59 | + self._registry[self] = info |
| 60 | + finalize._dirty = True |
| 61 | + |
| 62 | + def __call__(self, _=None): |
| 63 | + """If alive then mark as dead and return func(*args, **kwargs); |
| 64 | + otherwise return None""" |
| 65 | + info = self._registry.pop(self, None) |
| 66 | + if info and not self._shutdown: |
| 67 | + return info.func(*info.args, **(info.kwargs or {})) |
| 68 | + |
| 69 | + def detach(self): |
| 70 | + """If alive then mark as dead and return (obj, func, args, kwargs); |
| 71 | + otherwise return None""" |
| 72 | + info = self._registry.get(self) |
| 73 | + obj = info and info.weakref() |
| 74 | + if obj is not None and self._registry.pop(self, None): |
| 75 | + return (obj, info.func, info.args, info.kwargs or {}) |
| 76 | + |
| 77 | + def peek(self): |
| 78 | + """If alive then return (obj, func, args, kwargs); |
| 79 | + otherwise return None""" |
| 80 | + info = self._registry.get(self) |
| 81 | + obj = info and info.weakref() |
| 82 | + if obj is not None: |
| 83 | + return (obj, info.func, info.args, info.kwargs or {}) |
| 84 | + |
| 85 | + @property |
| 86 | + def alive(self): |
| 87 | + """Whether finalizer is alive""" |
| 88 | + return self in self._registry |
| 89 | + |
| 90 | + @property |
| 91 | + def atexit(self): |
| 92 | + """Whether finalizer should be called at exit""" |
| 93 | + info = self._registry.get(self) |
| 94 | + return bool(info) and info.atexit |
| 95 | + |
| 96 | + @atexit.setter |
| 97 | + def atexit(self, value): |
| 98 | + info = self._registry.get(self) |
| 99 | + if info: |
| 100 | + info.atexit = bool(value) |
| 101 | + |
| 102 | + def __repr__(self): |
| 103 | + info = self._registry.get(self) |
| 104 | + obj = info and info.weakref() |
| 105 | + if obj is None: |
| 106 | + return '<%s object at %#x; dead>' % (type(self).__name__, id(self)) |
| 107 | + else: |
| 108 | + return '<%s object at %#x; for %r at %#x>' % \ |
| 109 | + (type(self).__name__, id(self), type(obj).__name__, id(obj)) |
| 110 | + |
| 111 | + @classmethod |
| 112 | + def _select_for_exit(cls): |
| 113 | + # Return live finalizers marked for exit, oldest first |
| 114 | + L = [(f,i) for (f,i) in cls._registry.items() if i.atexit] |
| 115 | + L.sort(key=lambda item:item[1].index) |
| 116 | + return [f for (f,i) in L] |
| 117 | + |
| 118 | + @classmethod |
| 119 | + def _exitfunc(cls): |
| 120 | + # At shutdown invoke finalizers for which atexit is true. |
| 121 | + # This is called once all other non-daemonic threads have been |
| 122 | + # joined. |
| 123 | + reenable_gc = False |
| 124 | + try: |
| 125 | + if cls._registry: |
| 126 | + import gc |
| 127 | + if gc.isenabled(): |
| 128 | + reenable_gc = True |
| 129 | + gc.disable() |
| 130 | + pending = None |
| 131 | + while True: |
| 132 | + if pending is None or finalize._dirty: |
| 133 | + pending = cls._select_for_exit() |
| 134 | + finalize._dirty = False |
| 135 | + if not pending: |
| 136 | + break |
| 137 | + f = pending.pop() |
| 138 | + try: |
| 139 | + # gc is disabled, so (assuming no daemonic |
| 140 | + # threads) the following is the only line in |
| 141 | + # this function which might trigger creation |
| 142 | + # of a new finalizer |
| 143 | + f() |
| 144 | + except Exception: |
| 145 | + sys.excepthook(*sys.exc_info()) |
| 146 | + assert f not in cls._registry |
| 147 | + finally: |
| 148 | + # prevent any more finalizers from executing during shutdown |
| 149 | + finalize._shutdown = True |
| 150 | + if reenable_gc: |
| 151 | + gc.enable() |
0 commit comments