1:mod:`weakref` --- Weak references 2================================== 3 4.. module:: weakref 5 :synopsis: Support for weak references and weak dictionaries. 6 7.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org> 8.. moduleauthor:: Neil Schemenauer <nas@arctrix.com> 9.. moduleauthor:: Martin von Löwis <martin@loewis.home.cs.tu-berlin.de> 10.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> 11 12**Source code:** :source:`Lib/weakref.py` 13 14-------------- 15 16The :mod:`weakref` module allows the Python programmer to create :dfn:`weak 17references` to objects. 18 19.. When making changes to the examples in this file, be sure to update 20 Lib/test/test_weakref.py::libreftest too! 21 22In the following, the term :dfn:`referent` means the object which is referred to 23by a weak reference. 24 25A weak reference to an object is not enough to keep the object alive: when the 26only remaining references to a referent are weak references, 27:term:`garbage collection` is free to destroy the referent and reuse its memory 28for something else. However, until the object is actually destroyed the weak 29reference may return the object even if there are no strong references to it. 30 31A primary use for weak references is to implement caches or 32mappings holding large objects, where it's desired that a large object not be 33kept alive solely because it appears in a cache or mapping. 34 35For example, if you have a number of large binary image objects, you may wish to 36associate a name with each. If you used a Python dictionary to map names to 37images, or images to names, the image objects would remain alive just because 38they appeared as values or keys in the dictionaries. The 39:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by 40the :mod:`weakref` module are an alternative, using weak references to construct 41mappings that don't keep objects alive solely because they appear in the mapping 42objects. If, for example, an image object is a value in a 43:class:`WeakValueDictionary`, then when the last remaining references to that 44image object are the weak references held by weak mappings, garbage collection 45can reclaim the object, and its corresponding entries in weak mappings are 46simply deleted. 47 48:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references 49in their implementation, setting up callback functions on the weak references 50that notify the weak dictionaries when a key or value has been reclaimed by 51garbage collection. :class:`WeakSet` implements the :class:`set` interface, 52but keeps weak references to its elements, just like a 53:class:`WeakKeyDictionary` does. 54 55:class:`finalize` provides a straight forward way to register a 56cleanup function to be called when an object is garbage collected. 57This is simpler to use than setting up a callback function on a raw 58weak reference, since the module automatically ensures that the finalizer 59remains alive until the object is collected. 60 61Most programs should find that using one of these weak container types 62or :class:`finalize` is all they need -- it's not usually necessary to 63create your own weak references directly. The low-level machinery is 64exposed by the :mod:`weakref` module for the benefit of advanced uses. 65 66Not all objects can be weakly referenced; those objects which can include class 67instances, functions written in Python (but not in C), instance methods, sets, 68frozensets, some :term:`file objects <file object>`, :term:`generators <generator>`, 69type objects, sockets, arrays, deques, regular expression pattern objects, and code 70objects. 71 72.. versionchanged:: 3.2 73 Added support for thread.lock, threading.Lock, and code objects. 74 75Several built-in types such as :class:`list` and :class:`dict` do not directly 76support weak references but can add support through subclassing:: 77 78 class Dict(dict): 79 pass 80 81 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable 82 83.. impl-detail:: 84 85 Other built-in types such as :class:`tuple` and :class:`int` do not support weak 86 references even when subclassed. 87 88Extension types can easily be made to support weak references; see 89:ref:`weakref-support`. 90 91When ``__slots__`` are defined for a given type, weak reference support is 92disabled unless a ``'__weakref__'`` string is also present in the sequence of 93strings in the ``__slots__`` declaration. 94See :ref:`__slots__ documentation <slots>` for details. 95 96.. class:: ref(object[, callback]) 97 98 Return a weak reference to *object*. The original object can be retrieved by 99 calling the reference object if the referent is still alive; if the referent is 100 no longer alive, calling the reference object will cause :const:`None` to be 101 returned. If *callback* is provided and not :const:`None`, and the returned 102 weakref object is still alive, the callback will be called when the object is 103 about to be finalized; the weak reference object will be passed as the only 104 parameter to the callback; the referent will no longer be available. 105 106 It is allowable for many weak references to be constructed for the same object. 107 Callbacks registered for each weak reference will be called from the most 108 recently registered callback to the oldest registered callback. 109 110 Exceptions raised by the callback will be noted on the standard error output, 111 but cannot be propagated; they are handled in exactly the same way as exceptions 112 raised from an object's :meth:`__del__` method. 113 114 Weak references are :term:`hashable` if the *object* is hashable. They will 115 maintain their hash value even after the *object* was deleted. If 116 :func:`hash` is called the first time only after the *object* was deleted, 117 the call will raise :exc:`TypeError`. 118 119 Weak references support tests for equality, but not ordering. If the referents 120 are still alive, two references have the same equality relationship as their 121 referents (regardless of the *callback*). If either referent has been deleted, 122 the references are equal only if the reference objects are the same object. 123 124 This is a subclassable type rather than a factory function. 125 126 .. attribute:: __callback__ 127 128 This read-only attribute returns the callback currently associated to the 129 weakref. If there is no callback or if the referent of the weakref is 130 no longer alive then this attribute will have value ``None``. 131 132 .. versionchanged:: 3.4 133 Added the :attr:`__callback__` attribute. 134 135 136.. function:: proxy(object[, callback]) 137 138 Return a proxy to *object* which uses a weak reference. This supports use of 139 the proxy in most contexts instead of requiring the explicit dereferencing used 140 with weak reference objects. The returned object will have a type of either 141 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is 142 callable. Proxy objects are not :term:`hashable` regardless of the referent; this 143 avoids a number of problems related to their fundamentally mutable nature, and 144 prevent their use as dictionary keys. *callback* is the same as the parameter 145 of the same name to the :func:`ref` function. 146 147 .. versionchanged:: 3.8 148 Extended the operator support on proxy objects to include the matrix 149 multiplication operators ``@`` and ``@=``. 150 151 152.. function:: getweakrefcount(object) 153 154 Return the number of weak references and proxies which refer to *object*. 155 156 157.. function:: getweakrefs(object) 158 159 Return a list of all weak reference and proxy objects which refer to *object*. 160 161 162.. class:: WeakKeyDictionary([dict]) 163 164 Mapping class that references keys weakly. Entries in the dictionary will be 165 discarded when there is no longer a strong reference to the key. This can be 166 used to associate additional data with an object owned by other parts of an 167 application without adding attributes to those objects. This can be especially 168 useful with objects that override attribute accesses. 169 170 .. versionchanged:: 3.9 171 Added support for ``|`` and ``|=`` operators, specified in :pep:`584`. 172 173:class:`WeakKeyDictionary` objects have an additional method that 174exposes the internal references directly. The references are not guaranteed to 175be "live" at the time they are used, so the result of calling the references 176needs to be checked before being used. This can be used to avoid creating 177references that will cause the garbage collector to keep the keys around longer 178than needed. 179 180 181.. method:: WeakKeyDictionary.keyrefs() 182 183 Return an iterable of the weak references to the keys. 184 185 186.. class:: WeakValueDictionary([dict]) 187 188 Mapping class that references values weakly. Entries in the dictionary will be 189 discarded when no strong reference to the value exists any more. 190 191 .. versionchanged:: 3.9 192 Added support for ``|`` and ``|=`` operators, as specified in :pep:`584`. 193 194:class:`WeakValueDictionary` objects have an additional method that has the 195same issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary` 196objects. 197 198 199.. method:: WeakValueDictionary.valuerefs() 200 201 Return an iterable of the weak references to the values. 202 203 204.. class:: WeakSet([elements]) 205 206 Set class that keeps weak references to its elements. An element will be 207 discarded when no strong reference to it exists any more. 208 209 210.. class:: WeakMethod(method) 211 212 A custom :class:`ref` subclass which simulates a weak reference to a bound 213 method (i.e., a method defined on a class and looked up on an instance). 214 Since a bound method is ephemeral, a standard weak reference cannot keep 215 hold of it. :class:`WeakMethod` has special code to recreate the bound 216 method until either the object or the original function dies:: 217 218 >>> class C: 219 ... def method(self): 220 ... print("method called!") 221 ... 222 >>> c = C() 223 >>> r = weakref.ref(c.method) 224 >>> r() 225 >>> r = weakref.WeakMethod(c.method) 226 >>> r() 227 <bound method C.method of <__main__.C object at 0x7fc859830220>> 228 >>> r()() 229 method called! 230 >>> del c 231 >>> gc.collect() 232 0 233 >>> r() 234 >>> 235 236 .. versionadded:: 3.4 237 238.. class:: finalize(obj, func, /, *args, **kwargs) 239 240 Return a callable finalizer object which will be called when *obj* 241 is garbage collected. Unlike an ordinary weak reference, a finalizer 242 will always survive until the reference object is collected, greatly 243 simplifying lifecycle management. 244 245 A finalizer is considered *alive* until it is called (either explicitly 246 or at garbage collection), and after that it is *dead*. Calling a live 247 finalizer returns the result of evaluating ``func(*arg, **kwargs)``, 248 whereas calling a dead finalizer returns :const:`None`. 249 250 Exceptions raised by finalizer callbacks during garbage collection 251 will be shown on the standard error output, but cannot be 252 propagated. They are handled in the same way as exceptions raised 253 from an object's :meth:`__del__` method or a weak reference's 254 callback. 255 256 When the program exits, each remaining live finalizer is called 257 unless its :attr:`atexit` attribute has been set to false. They 258 are called in reverse order of creation. 259 260 A finalizer will never invoke its callback during the later part of 261 the :term:`interpreter shutdown` when module globals are liable to have 262 been replaced by :const:`None`. 263 264 .. method:: __call__() 265 266 If *self* is alive then mark it as dead and return the result of 267 calling ``func(*args, **kwargs)``. If *self* is dead then return 268 :const:`None`. 269 270 .. method:: detach() 271 272 If *self* is alive then mark it as dead and return the tuple 273 ``(obj, func, args, kwargs)``. If *self* is dead then return 274 :const:`None`. 275 276 .. method:: peek() 277 278 If *self* is alive then return the tuple ``(obj, func, args, 279 kwargs)``. If *self* is dead then return :const:`None`. 280 281 .. attribute:: alive 282 283 Property which is true if the finalizer is alive, false otherwise. 284 285 .. attribute:: atexit 286 287 A writable boolean property which by default is true. When the 288 program exits, it calls all remaining live finalizers for which 289 :attr:`.atexit` is true. They are called in reverse order of 290 creation. 291 292 .. note:: 293 294 It is important to ensure that *func*, *args* and *kwargs* do 295 not own any references to *obj*, either directly or indirectly, 296 since otherwise *obj* will never be garbage collected. In 297 particular, *func* should not be a bound method of *obj*. 298 299 .. versionadded:: 3.4 300 301 302.. data:: ReferenceType 303 304 The type object for weak references objects. 305 306 307.. data:: ProxyType 308 309 The type object for proxies of objects which are not callable. 310 311 312.. data:: CallableProxyType 313 314 The type object for proxies of callable objects. 315 316 317.. data:: ProxyTypes 318 319 Sequence containing all the type objects for proxies. This can make it simpler 320 to test if an object is a proxy without being dependent on naming both proxy 321 types. 322 323 324.. seealso:: 325 326 :pep:`205` - Weak References 327 The proposal and rationale for this feature, including links to earlier 328 implementations and information about similar features in other languages. 329 330 331.. _weakref-objects: 332 333Weak Reference Objects 334---------------------- 335 336Weak reference objects have no methods and no attributes besides 337:attr:`ref.__callback__`. A weak reference object allows the referent to be 338obtained, if it still exists, by calling it: 339 340 >>> import weakref 341 >>> class Object: 342 ... pass 343 ... 344 >>> o = Object() 345 >>> r = weakref.ref(o) 346 >>> o2 = r() 347 >>> o is o2 348 True 349 350If the referent no longer exists, calling the reference object returns 351:const:`None`: 352 353 >>> del o, o2 354 >>> print(r()) 355 None 356 357Testing that a weak reference object is still live should be done using the 358expression ``ref() is not None``. Normally, application code that needs to use 359a reference object should follow this pattern:: 360 361 # r is a weak reference object 362 o = r() 363 if o is None: 364 # referent has been garbage collected 365 print("Object has been deallocated; can't frobnicate.") 366 else: 367 print("Object is still live!") 368 o.do_something_useful() 369 370Using a separate test for "liveness" creates race conditions in threaded 371applications; another thread can cause a weak reference to become invalidated 372before the weak reference is called; the idiom shown above is safe in threaded 373applications as well as single-threaded applications. 374 375Specialized versions of :class:`ref` objects can be created through subclassing. 376This is used in the implementation of the :class:`WeakValueDictionary` to reduce 377the memory overhead for each entry in the mapping. This may be most useful to 378associate additional information with a reference, but could also be used to 379insert additional processing on calls to retrieve the referent. 380 381This example shows how a subclass of :class:`ref` can be used to store 382additional information about an object and affect the value that's returned when 383the referent is accessed:: 384 385 import weakref 386 387 class ExtendedRef(weakref.ref): 388 def __init__(self, ob, callback=None, /, **annotations): 389 super().__init__(ob, callback) 390 self.__counter = 0 391 for k, v in annotations.items(): 392 setattr(self, k, v) 393 394 def __call__(self): 395 """Return a pair containing the referent and the number of 396 times the reference has been called. 397 """ 398 ob = super().__call__() 399 if ob is not None: 400 self.__counter += 1 401 ob = (ob, self.__counter) 402 return ob 403 404 405.. _weakref-example: 406 407Example 408------- 409 410This simple example shows how an application can use object IDs to retrieve 411objects that it has seen before. The IDs of the objects can then be used in 412other data structures without forcing the objects to remain alive, but the 413objects can still be retrieved by ID if they do. 414 415.. Example contributed by Tim Peters. 416 417:: 418 419 import weakref 420 421 _id2obj_dict = weakref.WeakValueDictionary() 422 423 def remember(obj): 424 oid = id(obj) 425 _id2obj_dict[oid] = obj 426 return oid 427 428 def id2obj(oid): 429 return _id2obj_dict[oid] 430 431 432.. _finalize-examples: 433 434Finalizer Objects 435----------------- 436 437The main benefit of using :class:`finalize` is that it makes it simple 438to register a callback without needing to preserve the returned finalizer 439object. For instance 440 441 >>> import weakref 442 >>> class Object: 443 ... pass 444 ... 445 >>> kenny = Object() 446 >>> weakref.finalize(kenny, print, "You killed Kenny!") #doctest:+ELLIPSIS 447 <finalize object at ...; for 'Object' at ...> 448 >>> del kenny 449 You killed Kenny! 450 451The finalizer can be called directly as well. However the finalizer 452will invoke the callback at most once. 453 454 >>> def callback(x, y, z): 455 ... print("CALLBACK") 456 ... return x + y + z 457 ... 458 >>> obj = Object() 459 >>> f = weakref.finalize(obj, callback, 1, 2, z=3) 460 >>> assert f.alive 461 >>> assert f() == 6 462 CALLBACK 463 >>> assert not f.alive 464 >>> f() # callback not called because finalizer dead 465 >>> del obj # callback not called because finalizer dead 466 467You can unregister a finalizer using its :meth:`~finalize.detach` 468method. This kills the finalizer and returns the arguments passed to 469the constructor when it was created. 470 471 >>> obj = Object() 472 >>> f = weakref.finalize(obj, callback, 1, 2, z=3) 473 >>> f.detach() #doctest:+ELLIPSIS 474 (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3}) 475 >>> newobj, func, args, kwargs = _ 476 >>> assert not f.alive 477 >>> assert newobj is obj 478 >>> assert func(*args, **kwargs) == 6 479 CALLBACK 480 481Unless you set the :attr:`~finalize.atexit` attribute to 482:const:`False`, a finalizer will be called when the program exits if it 483is still alive. For instance 484 485.. doctest:: 486 :options: +SKIP 487 488 >>> obj = Object() 489 >>> weakref.finalize(obj, print, "obj dead or exiting") 490 <finalize object at ...; for 'Object' at ...> 491 >>> exit() 492 obj dead or exiting 493 494 495Comparing finalizers with :meth:`__del__` methods 496------------------------------------------------- 497 498Suppose we want to create a class whose instances represent temporary 499directories. The directories should be deleted with their contents 500when the first of the following events occurs: 501 502* the object is garbage collected, 503* the object's :meth:`remove` method is called, or 504* the program exits. 505 506We might try to implement the class using a :meth:`__del__` method as 507follows:: 508 509 class TempDir: 510 def __init__(self): 511 self.name = tempfile.mkdtemp() 512 513 def remove(self): 514 if self.name is not None: 515 shutil.rmtree(self.name) 516 self.name = None 517 518 @property 519 def removed(self): 520 return self.name is None 521 522 def __del__(self): 523 self.remove() 524 525Starting with Python 3.4, :meth:`__del__` methods no longer prevent 526reference cycles from being garbage collected, and module globals are 527no longer forced to :const:`None` during :term:`interpreter shutdown`. 528So this code should work without any issues on CPython. 529 530However, handling of :meth:`__del__` methods is notoriously implementation 531specific, since it depends on internal details of the interpreter's garbage 532collector implementation. 533 534A more robust alternative can be to define a finalizer which only references 535the specific functions and objects that it needs, rather than having access 536to the full state of the object:: 537 538 class TempDir: 539 def __init__(self): 540 self.name = tempfile.mkdtemp() 541 self._finalizer = weakref.finalize(self, shutil.rmtree, self.name) 542 543 def remove(self): 544 self._finalizer() 545 546 @property 547 def removed(self): 548 return not self._finalizer.alive 549 550Defined like this, our finalizer only receives a reference to the details 551it needs to clean up the directory appropriately. If the object never gets 552garbage collected the finalizer will still be called at exit. 553 554The other advantage of weakref based finalizers is that they can be used to 555register finalizers for classes where the definition is controlled by a 556third party, such as running code when a module is unloaded:: 557 558 import weakref, sys 559 def unloading_module(): 560 # implicit reference to the module globals from the function body 561 weakref.finalize(sys.modules[__name__], unloading_module) 562 563 564.. note:: 565 566 If you create a finalizer object in a daemonic thread just as the program 567 exits then there is the possibility that the finalizer 568 does not get called at exit. However, in a daemonic thread 569 :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...`` 570 do not guarantee that cleanup occurs either. 571