"""Weak reference support for Python.
This module is an implementation of PEP 205:
http://www.python.org/dev/peps/pep-0205/
# Naming convention: Variables named "wr" are weak reference objects;
# they are called this instead of "ref" to avoid name collisions with
# the module-global ref() function imported from _weakref.
from _weakrefset import WeakSet, _IterationGuard
import _collections_abc # Import after _weakref to avoid circular import.
ProxyTypes = (ProxyType, CallableProxyType)
__all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
"WeakKeyDictionary", "ReferenceType", "ProxyType",
"CallableProxyType", "ProxyTypes", "WeakValueDictionary",
"WeakSet", "WeakMethod", "finalize"]
A custom `weakref.ref` subclass which simulates a weak reference to
a bound method, working around the lifetime problem of bound methods.
__slots__ = "_func_ref", "_meth_type", "_alive", "__weakref__"
def __new__(cls, meth, callback=None):
raise TypeError("argument should be a bound method, not {}"
.format(type(meth))) from None
# The self-weakref trick is needed to avoid creating a reference
self = ref.__new__(cls, obj, _cb)
self._func_ref = ref(func, _cb)
self._meth_type = type(meth)
if obj is None or func is None:
return self._meth_type(func, obj)
if isinstance(other, WeakMethod):
if not self._alive or not other._alive:
return ref.__eq__(self, other) and self._func_ref == other._func_ref
if isinstance(other, WeakMethod):
if not self._alive or not other._alive:
return ref.__ne__(self, other) or self._func_ref != other._func_ref
class WeakValueDictionary(_collections_abc.MutableMapping):
"""Mapping class that references values weakly.
Entries in the dictionary will be discarded when no strong
reference to the value exists anymore
# We inherit the constructor without worrying about the input
# dictionary; since it uses our .update() method, we get the right
# checks (if the other dictionary is a WeakValueDictionary,
# objects are unwrapped on the way out, and we always wrap on the
def __init__(self, other=(), /, **kw):
def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref):
self._pending_removals.append(wr.key)
# Atomic removal is necessary since this function
# can be called asynchronously by the GC
_atomic_removal(self.data, wr.key)
# A list of keys to be removed
self._pending_removals = []
def _commit_removals(self):
l = self._pending_removals
# We shouldn't encounter any KeyError, because this method should
# always be called *before* mutating the dict.
_remove_dead_weakref(d, key)
def __getitem__(self, key):
if self._pending_removals:
def __delitem__(self, key):
if self._pending_removals:
if self._pending_removals:
def __contains__(self, key):
if self._pending_removals:
return "<%s at %#x>" % (self.__class__.__name__, id(self))
def __setitem__(self, key, value):
if self._pending_removals:
self.data[key] = KeyedRef(value, self._remove, key)
if self._pending_removals:
new = WeakValueDictionary()
with _IterationGuard(self):
for key, wr in self.data.items():
def __deepcopy__(self, memo):
from copy import deepcopy
if self._pending_removals:
with _IterationGuard(self):
for key, wr in self.data.items():
new[deepcopy(key, memo)] = o
def get(self, key, default=None):
if self._pending_removals:
# This should only happen
if self._pending_removals:
with _IterationGuard(self):
for k, wr in self.data.items():
if self._pending_removals:
with _IterationGuard(self):
for k, wr in self.data.items():
"""Return an iterator that yields the weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed.
if self._pending_removals:
with _IterationGuard(self):
yield from self.data.values()
if self._pending_removals:
with _IterationGuard(self):
for wr in self.data.values():
if self._pending_removals:
key, wr = self.data.popitem()
def pop(self, key, *args):
if self._pending_removals:
def setdefault(self, key, default=None):
if self._pending_removals:
self.data[key] = KeyedRef(default, self._remove, key)
def update(self, other=None, /, **kwargs):
if self._pending_removals:
if not hasattr(other, "items"):
for key, o in other.items():
d[key] = KeyedRef(o, self._remove, key)
for key, o in kwargs.items():
d[key] = KeyedRef(o, self._remove, key)
"""Return a list of weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed.
if self._pending_removals:
return list(self.data.values())
"""Specialized reference that includes a key corresponding to the value.
This is used in the WeakValueDictionary to avoid having to create
a function object for each key stored in the mapping. A shared
callback object can use the 'key' attribute of a KeyedRef instead
of getting a reference to the key from an enclosing scope.
def __new__(type, ob, callback, key):
self = ref.__new__(type, ob, callback)
def __init__(self, ob, callback, key):
super().__init__(ob, callback)
class WeakKeyDictionary(_collections_abc.MutableMapping):
""" Mapping class that references keys weakly.
Entries in the dictionary will be discarded when there is no
longer a strong reference to the key. This can be used to
associate additional data with an object owned by other parts of
an application without adding attributes to those objects. This
can be especially useful with objects that override attribute
def __init__(self, dict=None):
def remove(k, selfref=ref(self)):
self._pending_removals.append(k)
# A list of dead weakrefs (keys to be removed)
self._pending_removals = []
def _commit_removals(self):
# NOTE: We don't need to call this method before mutating the dict,
# because a dead weakref never compares equal to a live weakref,
# even if they happened to refer to equal objects.
# However, it means keys may already have been removed.
l = self._pending_removals
def _scrub_removals(self):
self._pending_removals = [k for k in self._pending_removals if k in d]
def __delitem__(self, key):
def __getitem__(self, key):
return self.data[ref(key)]
if self._dirty_len and self._pending_removals:
# self._pending_removals may still contain keys which were
# explicitly removed, we have to scrub them (see issue #21173).
return len(self.data) - len(self._pending_removals)
return "<%s at %#x>" % (self.__class__.__name__, id(self))
def __setitem__(self, key, value):
self.data[ref(key, self._remove)] = value
new = WeakKeyDictionary()
with _IterationGuard(self):
for key, value in self.data.items():
def __deepcopy__(self, memo):
from copy import deepcopy
with _IterationGuard(self):
for key, value in self.data.items():
new[o] = deepcopy(value, memo)
def get(self, key, default=None):
return self.data.get(ref(key),default)
def __contains__(self, key):
with _IterationGuard(self):
for wr, value in self.data.items():
with _IterationGuard(self):
with _IterationGuard(self):
for wr, value in self.data.items():
"""Return a list of weak references to the keys.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer than needed.
key, value = self.data.popitem()
def pop(self, key, *args):
return self.data.pop(ref(key), *args)
def setdefault(self, key, default=None):
return self.data.setdefault(ref(key, self._remove),default)
def update(self, dict=None, /, **kwargs):
if not hasattr(dict, "items"):
for key, value in dict.items():
d[ref(key, self._remove)] = value
"""Class for finalization of weakrefable objects
finalize(obj, func, *args, **kwargs) returns a callable finalizer
object which will be called when obj is garbage collected. The
first time the finalizer is called it evaluates func(*arg, **kwargs)
and returns the result. After this the finalizer is dead, and
calling it just returns None.
When the program exits any remaining finalizers for which the
atexit attribute is true will be run in reverse order of creation.
By default atexit is true.