blob: c10f436bea4c4e4e11862d7416b6b88b2d7590ae [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`weakref` --- Weak references
2==================================
3
4.. module:: weakref
5 :synopsis: Support for weak references and weak dictionaries.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. 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
Raymond Hettinger469271d2011-01-27 20:38:46 +000012**Source code:** :source:`Lib/weakref.py`
13
14--------------
Georg Brandl116aa622007-08-15 14:28:22 +000015
Georg Brandl116aa622007-08-15 14:28:22 +000016The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
17references` to objects.
18
Christian Heimes5b5e81c2007-12-31 16:14:33 +000019.. When making changes to the examples in this file, be sure to update
20 Lib/test/test_weakref.py::libreftest too!
Georg Brandl116aa622007-08-15 14:28:22 +000021
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
Christian Heimesd8654cf2007-12-02 15:22:16 +000026only remaining references to a referent are weak references,
27:term:`garbage collection` is free to destroy the referent and reuse its memory
Antoine Pitrou9439f042012-08-21 00:07:07 +020028for 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
Christian Heimesd8654cf2007-12-02 15:22:16 +000032mappings holding large objects, where it's desired that a large object not be
Christian Heimesfe337bf2008-03-23 21:54:12 +000033kept 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.
Georg Brandl116aa622007-08-15 14:28:22 +000047
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
Georg Brandl3b8cb172007-10-23 06:26:46 +000051garbage collection. :class:`WeakSet` implements the :class:`set` interface,
52but keeps weak references to its elements, just like a
53:class:`WeakKeyDictionary` does.
54
Richard Oudkerk7a3dae052013-05-05 23:05:00 +010055: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
Nick Coghlanbe57ab82013-09-22 21:26:30 +100058weak reference, since the module automatically ensures that the finalizer
59remains alive until the object is collected.
Richard Oudkerk7a3dae052013-05-05 23:05:00 +010060
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.
Georg Brandl116aa622007-08-15 14:28:22 +000065
66Not all objects can be weakly referenced; those objects which can include class
Georg Brandl2e0b7552007-11-27 12:43:08 +000067instances, functions written in Python (but not in C), instance methods, sets,
Géry Ogamf4757292019-06-15 13:33:23 +020068frozensets, some :term:`file objects <file object>`, :term:`generators <generator>`,
69type objects, sockets, arrays, deques, regular expression pattern objects, and code
Antoine Pitrou11cb9612010-09-15 11:11:28 +000070objects.
Georg Brandl116aa622007-08-15 14:28:22 +000071
Benjamin Petersonbec4d572009-10-10 01:16:07 +000072.. versionchanged:: 3.2
Collin Winter4222e9c2010-03-18 22:46:40 +000073 Added support for thread.lock, threading.Lock, and code objects.
Benjamin Petersonbec4d572009-10-10 01:16:07 +000074
Georg Brandl22b34312009-07-26 14:54:51 +000075Several built-in types such as :class:`list` and :class:`dict` do not directly
Georg Brandl116aa622007-08-15 14:28:22 +000076support weak references but can add support through subclassing::
77
78 class Dict(dict):
79 pass
80
Christian Heimesc3f30c42008-02-22 16:37:40 +000081 obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable
Georg Brandl116aa622007-08-15 14:28:22 +000082
Géry Ogamf4757292019-06-15 13:33:23 +020083.. impl-detail::
84
85 Other built-in types such as :class:`tuple` and :class:`int` do not support weak
86 references even when subclassed.
Georg Brandlff8c1e52009-10-21 07:17:48 +000087
Georg Brandl116aa622007-08-15 14:28:22 +000088Extension types can easily be made to support weak references; see
89:ref:`weakref-support`.
90
91
92.. class:: ref(object[, callback])
93
94 Return a weak reference to *object*. The original object can be retrieved by
95 calling the reference object if the referent is still alive; if the referent is
96 no longer alive, calling the reference object will cause :const:`None` to be
97 returned. If *callback* is provided and not :const:`None`, and the returned
98 weakref object is still alive, the callback will be called when the object is
99 about to be finalized; the weak reference object will be passed as the only
100 parameter to the callback; the referent will no longer be available.
101
102 It is allowable for many weak references to be constructed for the same object.
103 Callbacks registered for each weak reference will be called from the most
104 recently registered callback to the oldest registered callback.
105
106 Exceptions raised by the callback will be noted on the standard error output,
107 but cannot be propagated; they are handled in exactly the same way as exceptions
108 raised from an object's :meth:`__del__` method.
109
Georg Brandl7f01a132009-09-16 15:58:14 +0000110 Weak references are :term:`hashable` if the *object* is hashable. They will
111 maintain their hash value even after the *object* was deleted. If
112 :func:`hash` is called the first time only after the *object* was deleted,
113 the call will raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115 Weak references support tests for equality, but not ordering. If the referents
116 are still alive, two references have the same equality relationship as their
117 referents (regardless of the *callback*). If either referent has been deleted,
118 the references are equal only if the reference objects are the same object.
119
Georg Brandl55ac8f02007-09-01 13:51:09 +0000120 This is a subclassable type rather than a factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Mark Dickinson556e94b2013-04-13 15:45:44 +0100122 .. attribute:: __callback__
123
124 This read-only attribute returns the callback currently associated to the
125 weakref. If there is no callback or if the referent of the weakref is
126 no longer alive then this attribute will have value ``None``.
127
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100128 .. versionchanged:: 3.4
Mark Dickinson9b6fdf82013-04-13 16:09:18 +0100129 Added the :attr:`__callback__` attribute.
Mark Dickinson556e94b2013-04-13 15:45:44 +0100130
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132.. function:: proxy(object[, callback])
133
134 Return a proxy to *object* which uses a weak reference. This supports use of
135 the proxy in most contexts instead of requiring the explicit dereferencing used
136 with weak reference objects. The returned object will have a type of either
137 ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000138 callable. Proxy objects are not :term:`hashable` regardless of the referent; this
Georg Brandl116aa622007-08-15 14:28:22 +0000139 avoids a number of problems related to their fundamentally mutable nature, and
140 prevent their use as dictionary keys. *callback* is the same as the parameter
141 of the same name to the :func:`ref` function.
142
Mark Dickinson7abb6c02019-04-26 15:56:15 +0900143 .. versionchanged:: 3.8
144 Extended the operator support on proxy objects to include the matrix
145 multiplication operators ``@`` and ``@=``.
146
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148.. function:: getweakrefcount(object)
149
150 Return the number of weak references and proxies which refer to *object*.
151
152
153.. function:: getweakrefs(object)
154
155 Return a list of all weak reference and proxy objects which refer to *object*.
156
157
158.. class:: WeakKeyDictionary([dict])
159
160 Mapping class that references keys weakly. Entries in the dictionary will be
161 discarded when there is no longer a strong reference to the key. This can be
162 used to associate additional data with an object owned by other parts of an
163 application without adding attributes to those objects. This can be especially
164 useful with objects that override attribute accesses.
165
166 .. note::
167
Christian Heimesfe337bf2008-03-23 21:54:12 +0000168 Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
Georg Brandl116aa622007-08-15 14:28:22 +0000169 dictionary, it must not change size when iterating over it. This can be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000170 difficult to ensure for a :class:`WeakKeyDictionary` because actions
171 performed by the program during iteration may cause items in the
172 dictionary to vanish "by magic" (as a side effect of garbage collection).
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Curtis Bucher25e580a2020-03-23 13:49:46 -0700174 .. versionchanged:: 3.9
175 Added support for ``|`` and ``|=`` operators, specified in :pep:`584`.
176
Mariatta3110a372017-02-12 08:17:50 -0800177:class:`WeakKeyDictionary` objects have an additional method that
178exposes the internal references directly. The references are not guaranteed to
Georg Brandl116aa622007-08-15 14:28:22 +0000179be "live" at the time they are used, so the result of calling the references
180needs to be checked before being used. This can be used to avoid creating
181references that will cause the garbage collector to keep the keys around longer
182than needed.
183
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185.. method:: WeakKeyDictionary.keyrefs()
186
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000187 Return an iterable of the weak references to the keys.
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190.. class:: WeakValueDictionary([dict])
191
192 Mapping class that references values weakly. Entries in the dictionary will be
193 discarded when no strong reference to the value exists any more.
194
195 .. note::
196
197 Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
198 dictionary, it must not change size when iterating over it. This can be
199 difficult to ensure for a :class:`WeakValueDictionary` because actions performed
200 by the program during iteration may cause items in the dictionary to vanish "by
201 magic" (as a side effect of garbage collection).
202
Mariatta3110a372017-02-12 08:17:50 -0800203:class:`WeakValueDictionary` objects have an additional method that has the
204same issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary`
205objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208.. method:: WeakValueDictionary.valuerefs()
209
Antoine Pitrouc1baa602010-01-08 17:54:23 +0000210 Return an iterable of the weak references to the values.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Georg Brandl3b8cb172007-10-23 06:26:46 +0000213.. class:: WeakSet([elements])
214
215 Set class that keeps weak references to its elements. An element will be
216 discarded when no strong reference to it exists any more.
217
218
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100219.. class:: WeakMethod(method)
220
221 A custom :class:`ref` subclass which simulates a weak reference to a bound
222 method (i.e., a method defined on a class and looked up on an instance).
223 Since a bound method is ephemeral, a standard weak reference cannot keep
224 hold of it. :class:`WeakMethod` has special code to recreate the bound
225 method until either the object or the original function dies::
226
227 >>> class C:
228 ... def method(self):
229 ... print("method called!")
230 ...
231 >>> c = C()
232 >>> r = weakref.ref(c.method)
233 >>> r()
234 >>> r = weakref.WeakMethod(c.method)
235 >>> r()
236 <bound method C.method of <__main__.C object at 0x7fc859830220>>
237 >>> r()()
238 method called!
239 >>> del c
240 >>> gc.collect()
241 0
242 >>> r()
243 >>>
244
245 .. versionadded:: 3.4
246
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300247.. class:: finalize(obj, func, /, *args, **kwargs)
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100248
249 Return a callable finalizer object which will be called when *obj*
R David Murraya101bdb2014-01-06 16:32:05 -0500250 is garbage collected. Unlike an ordinary weak reference, a finalizer
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000251 will always survive until the reference object is collected, greatly
252 simplifying lifecycle management.
253
254 A finalizer is considered *alive* until it is called (either explicitly
255 or at garbage collection), and after that it is *dead*. Calling a live
256 finalizer returns the result of evaluating ``func(*arg, **kwargs)``,
257 whereas calling a dead finalizer returns :const:`None`.
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100258
259 Exceptions raised by finalizer callbacks during garbage collection
260 will be shown on the standard error output, but cannot be
261 propagated. They are handled in the same way as exceptions raised
262 from an object's :meth:`__del__` method or a weak reference's
263 callback.
264
265 When the program exits, each remaining live finalizer is called
266 unless its :attr:`atexit` attribute has been set to false. They
267 are called in reverse order of creation.
268
269 A finalizer will never invoke its callback during the later part of
Antoine Pitrou5db1bb82014-12-07 01:28:27 +0100270 the :term:`interpreter shutdown` when module globals are liable to have
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100271 been replaced by :const:`None`.
272
273 .. method:: __call__()
274
275 If *self* is alive then mark it as dead and return the result of
276 calling ``func(*args, **kwargs)``. If *self* is dead then return
277 :const:`None`.
278
279 .. method:: detach()
280
281 If *self* is alive then mark it as dead and return the tuple
282 ``(obj, func, args, kwargs)``. If *self* is dead then return
283 :const:`None`.
284
285 .. method:: peek()
286
287 If *self* is alive then return the tuple ``(obj, func, args,
288 kwargs)``. If *self* is dead then return :const:`None`.
289
290 .. attribute:: alive
291
292 Property which is true if the finalizer is alive, false otherwise.
293
294 .. attribute:: atexit
295
296 A writable boolean property which by default is true. When the
297 program exits, it calls all remaining live finalizers for which
298 :attr:`.atexit` is true. They are called in reverse order of
299 creation.
300
301 .. note::
302
303 It is important to ensure that *func*, *args* and *kwargs* do
304 not own any references to *obj*, either directly or indirectly,
305 since otherwise *obj* will never be garbage collected. In
306 particular, *func* should not be a bound method of *obj*.
307
308 .. versionadded:: 3.4
309
Antoine Pitrouc3afba12012-11-17 18:57:38 +0100310
Georg Brandl116aa622007-08-15 14:28:22 +0000311.. data:: ReferenceType
312
313 The type object for weak references objects.
314
315
316.. data:: ProxyType
317
318 The type object for proxies of objects which are not callable.
319
320
321.. data:: CallableProxyType
322
323 The type object for proxies of callable objects.
324
325
326.. data:: ProxyTypes
327
328 Sequence containing all the type objects for proxies. This can make it simpler
329 to test if an object is a proxy without being dependent on naming both proxy
330 types.
331
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333.. seealso::
334
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300335 :pep:`205` - Weak References
Georg Brandl116aa622007-08-15 14:28:22 +0000336 The proposal and rationale for this feature, including links to earlier
337 implementations and information about similar features in other languages.
338
339
340.. _weakref-objects:
341
342Weak Reference Objects
343----------------------
344
Mark Dickinson556e94b2013-04-13 15:45:44 +0100345Weak reference objects have no methods and no attributes besides
346:attr:`ref.__callback__`. A weak reference object allows the referent to be
347obtained, if it still exists, by calling it:
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349 >>> import weakref
350 >>> class Object:
351 ... pass
352 ...
353 >>> o = Object()
354 >>> r = weakref.ref(o)
355 >>> o2 = r()
356 >>> o is o2
357 True
358
359If the referent no longer exists, calling the reference object returns
Christian Heimesfe337bf2008-03-23 21:54:12 +0000360:const:`None`:
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 >>> del o, o2
Collin Winterc79461b2007-09-01 23:34:30 +0000363 >>> print(r())
Georg Brandl116aa622007-08-15 14:28:22 +0000364 None
365
366Testing that a weak reference object is still live should be done using the
367expression ``ref() is not None``. Normally, application code that needs to use
368a reference object should follow this pattern::
369
370 # r is a weak reference object
371 o = r()
372 if o is None:
373 # referent has been garbage collected
Collin Winterc79461b2007-09-01 23:34:30 +0000374 print("Object has been deallocated; can't frobnicate.")
Georg Brandl116aa622007-08-15 14:28:22 +0000375 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000376 print("Object is still live!")
Georg Brandl116aa622007-08-15 14:28:22 +0000377 o.do_something_useful()
378
379Using a separate test for "liveness" creates race conditions in threaded
380applications; another thread can cause a weak reference to become invalidated
381before the weak reference is called; the idiom shown above is safe in threaded
382applications as well as single-threaded applications.
383
384Specialized versions of :class:`ref` objects can be created through subclassing.
385This is used in the implementation of the :class:`WeakValueDictionary` to reduce
386the memory overhead for each entry in the mapping. This may be most useful to
387associate additional information with a reference, but could also be used to
388insert additional processing on calls to retrieve the referent.
389
390This example shows how a subclass of :class:`ref` can be used to store
391additional information about an object and affect the value that's returned when
392the referent is accessed::
393
394 import weakref
395
396 class ExtendedRef(weakref.ref):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300397 def __init__(self, ob, callback=None, /, **annotations):
Georg Brandl116aa622007-08-15 14:28:22 +0000398 super(ExtendedRef, self).__init__(ob, callback)
399 self.__counter = 0
Barry Warsawecaab832008-09-04 01:42:51 +0000400 for k, v in annotations.items():
Georg Brandl116aa622007-08-15 14:28:22 +0000401 setattr(self, k, v)
402
403 def __call__(self):
404 """Return a pair containing the referent and the number of
405 times the reference has been called.
406 """
407 ob = super(ExtendedRef, self).__call__()
408 if ob is not None:
409 self.__counter += 1
410 ob = (ob, self.__counter)
411 return ob
412
413
414.. _weakref-example:
415
416Example
417-------
418
Martin Panter0f0eac42016-09-07 11:04:41 +0000419This simple example shows how an application can use object IDs to retrieve
Georg Brandl116aa622007-08-15 14:28:22 +0000420objects that it has seen before. The IDs of the objects can then be used in
421other data structures without forcing the objects to remain alive, but the
422objects can still be retrieved by ID if they do.
423
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000424.. Example contributed by Tim Peters.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426::
427
428 import weakref
429
430 _id2obj_dict = weakref.WeakValueDictionary()
431
432 def remember(obj):
433 oid = id(obj)
434 _id2obj_dict[oid] = obj
435 return oid
436
437 def id2obj(oid):
438 return _id2obj_dict[oid]
439
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100440
441.. _finalize-examples:
442
443Finalizer Objects
444-----------------
445
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000446The main benefit of using :class:`finalize` is that it makes it simple
447to register a callback without needing to preserve the returned finalizer
448object. For instance
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100449
450 >>> import weakref
451 >>> class Object:
452 ... pass
453 ...
454 >>> kenny = Object()
455 >>> weakref.finalize(kenny, print, "You killed Kenny!") #doctest:+ELLIPSIS
456 <finalize object at ...; for 'Object' at ...>
457 >>> del kenny
458 You killed Kenny!
459
460The finalizer can be called directly as well. However the finalizer
461will invoke the callback at most once.
462
463 >>> def callback(x, y, z):
464 ... print("CALLBACK")
465 ... return x + y + z
466 ...
467 >>> obj = Object()
468 >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
469 >>> assert f.alive
470 >>> assert f() == 6
471 CALLBACK
472 >>> assert not f.alive
473 >>> f() # callback not called because finalizer dead
474 >>> del obj # callback not called because finalizer dead
475
476You can unregister a finalizer using its :meth:`~finalize.detach`
477method. This kills the finalizer and returns the arguments passed to
478the constructor when it was created.
479
480 >>> obj = Object()
481 >>> f = weakref.finalize(obj, callback, 1, 2, z=3)
482 >>> f.detach() #doctest:+ELLIPSIS
Marco Buttu7b2491a2017-04-13 16:17:59 +0200483 (<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100484 >>> newobj, func, args, kwargs = _
485 >>> assert not f.alive
486 >>> assert newobj is obj
487 >>> assert func(*args, **kwargs) == 6
488 CALLBACK
489
490Unless you set the :attr:`~finalize.atexit` attribute to
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000491:const:`False`, a finalizer will be called when the program exits if it
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100492is still alive. For instance
493
Inada Naokib3c92c62019-04-11 19:05:32 +0900494.. doctest::
495 :options: +SKIP
496
497 >>> obj = Object()
498 >>> weakref.finalize(obj, print, "obj dead or exiting")
499 <finalize object at ...; for 'Object' at ...>
500 >>> exit()
501 obj dead or exiting
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100502
503
504Comparing finalizers with :meth:`__del__` methods
505-------------------------------------------------
506
507Suppose we want to create a class whose instances represent temporary
508directories. The directories should be deleted with their contents
509when the first of the following events occurs:
510
511* the object is garbage collected,
512* the object's :meth:`remove` method is called, or
513* the program exits.
514
515We might try to implement the class using a :meth:`__del__` method as
516follows::
517
518 class TempDir:
519 def __init__(self):
520 self.name = tempfile.mkdtemp()
521
522 def remove(self):
523 if self.name is not None:
524 shutil.rmtree(self.name)
525 self.name = None
526
527 @property
528 def removed(self):
529 return self.name is None
530
531 def __del__(self):
532 self.remove()
533
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000534Starting with Python 3.4, :meth:`__del__` methods no longer prevent
535reference cycles from being garbage collected, and module globals are
Antoine Pitrou5db1bb82014-12-07 01:28:27 +0100536no longer forced to :const:`None` during :term:`interpreter shutdown`.
537So this code should work without any issues on CPython.
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100538
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000539However, handling of :meth:`__del__` methods is notoriously implementation
Nick Coghlan4c7fe6a2013-09-22 21:32:12 +1000540specific, since it depends on internal details of the interpreter's garbage
541collector implementation.
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000542
543A more robust alternative can be to define a finalizer which only references
544the specific functions and objects that it needs, rather than having access
545to the full state of the object::
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100546
547 class TempDir:
548 def __init__(self):
549 self.name = tempfile.mkdtemp()
550 self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
551
552 def remove(self):
553 self._finalizer()
554
555 @property
556 def removed(self):
557 return not self._finalizer.alive
558
Nick Coghlanbe57ab82013-09-22 21:26:30 +1000559Defined like this, our finalizer only receives a reference to the details
560it needs to clean up the directory appropriately. If the object never gets
561garbage collected the finalizer will still be called at exit.
562
563The other advantage of weakref based finalizers is that they can be used to
564register finalizers for classes where the definition is controlled by a
565third party, such as running code when a module is unloaded::
566
567 import weakref, sys
568 def unloading_module():
569 # implicit reference to the module globals from the function body
570 weakref.finalize(sys.modules[__name__], unloading_module)
571
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100572
573.. note::
574
Donald Stufft8b852f12014-05-20 12:58:38 -0400575 If you create a finalizer object in a daemonic thread just as the program
576 exits then there is the possibility that the finalizer
Richard Oudkerk7a3dae052013-05-05 23:05:00 +0100577 does not get called at exit. However, in a daemonic thread
578 :func:`atexit.register`, ``try: ... finally: ...`` and ``with: ...``
579 do not guarantee that cleanup occurs either.