Skip to content

Commit be57ab8

Browse files
committed
Close #19047: weakref doc cleanups
- be clear finalizers survive automatically - update for PEP 442 __del__ changes - mention module cleanup changes and weakref.finalize in What's New
1 parent a283887 commit be57ab8

2 files changed

Lines changed: 47 additions & 21 deletions

File tree

‎Doc/library/weakref.rst‎

Lines changed: 38 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ but keeps weak references to its elements, just like a
5454
:class:`finalize` provides a straight forward way to register a
5555
cleanup function to be called when an object is garbage collected.
5656
This is simpler to use than setting up a callback function on a raw
57-
weak reference.
57+
weak reference, since the module automatically ensures that the finalizer
58+
remains alive until the object is collected.
5859

5960
Most programs should find that using one of these weak container types
6061
or :class:`finalize` is all they need -- it's not usually necessary to
@@ -246,11 +247,14 @@ These method have the same issues as the and :meth:`keyrefs` method of
246247
.. class:: finalize(obj, func, *args, **kwargs)
247248

248249
Return a callable finalizer object which will be called when *obj*
249-
is garbage collected. A finalizer is *alive* until it is called
250-
(either explicitly or at garbage collection), and after that it is
251-
*dead*. Calling a live finalizer returns the result of evaluating
252-
``func(*arg, **kwargs)``, whereas calling a dead finalizer returns
253-
:const:`None`.
250+
is garbage collected. Unlike an ordinary weak reference, a finalizer is
251+
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`.
254258

255259
Exceptions raised by finalizer callbacks during garbage collection
256260
will be shown on the standard error output, but cannot be
@@ -445,8 +449,9 @@ objects can still be retrieved by ID if they do.
445449
Finalizer Objects
446450
-----------------
447451

448-
Often one uses :class:`finalize` to register a callback without
449-
bothering to keep the returned finalizer object. For instance
452+
The main benefit of using :class:`finalize` is that it makes it simple
453+
to register a callback without needing to preserve the returned finalizer
454+
object. For instance
450455

451456
>>> import weakref
452457
>>> class Object:
@@ -489,7 +494,7 @@ the constructor when it was created.
489494
CALLBACK
490495

491496
Unless you set the :attr:`~finalize.atexit` attribute to
492-
:const:`False`, a finalizer will be called when the program exit if it
497+
:const:`False`, a finalizer will be called when the program exits if it
493498
is still alive. For instance
494499

495500
>>> obj = Object()
@@ -529,13 +534,18 @@ follows::
529534
def __del__(self):
530535
self.remove()
531536

532-
This solution has a serious problem: the :meth:`__del__` method may be
533-
called at shutdown after the :mod:`shutil` module has been cleaned up,
534-
in which case :attr:`shutil.rmtree` will have been replaced by :const:`None`.
535-
This will cause the :meth:`__del__` method to fail and the directory
536-
will not be removed.
537+
Starting with Python 3.4, :meth:`__del__` methods no longer prevent
538+
reference cycles from being garbage collected, and module globals are
539+
no longer forced to :const:`None` during interpreter shutdown. So this
540+
code should work without any issues on CPython.
541+
542+
However, handling of :meth:`__del__` methods is notoriously implementation
543+
specific, since it depends on how the interpreter's garbage collector
544+
handles reference cycles and finalizers.
537545

538-
Using finalizers we can avoid this problem::
546+
A more robust alternative can be to define a finalizer which only references
547+
the specific functions and objects that it needs, rather than having access
548+
to the full state of the object::
539549

540550
class TempDir:
541551
def __init__(self):
@@ -549,10 +559,19 @@ Using finalizers we can avoid this problem::
549559
def removed(self):
550560
return not self._finalizer.alive
551561

552-
Defined like this, even if a :class:`TempDir` object is part of a
553-
reference cycle, that reference cycle can still be garbage collected.
554-
If the object never gets garbage collected the finalizer will still be
555-
called at exit.
562+
Defined like this, our finalizer only receives a reference to the details
563+
it needs to clean up the directory appropriately. If the object never gets
564+
garbage collected the finalizer will still be called at exit.
565+
566+
The other advantage of weakref based finalizers is that they can be used to
567+
register finalizers for classes where the definition is controlled by a
568+
third party, such as running code when a module is unloaded::
569+
570+
import weakref, sys
571+
def unloading_module():
572+
# implicit reference to the module globals from the function body
573+
weakref.finalize(sys.modules[__name__], unloading_module)
574+
556575

557576
.. note::
558577

‎Doc/whatsnew/3.4.rst‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,10 @@ With it, objects with :meth:`__del__` methods, as well as generators
153153
with :keyword:`finally` clauses, can be finalized when they are part of a
154154
reference cycle.
155155

156+
As part of this change, module globals are no longer forcibly set to
157+
:const:`None` during interpreter shutdown, instead relying on the normal
158+
operation of the cyclic garbage collector.
159+
156160
.. seealso::
157161

158162
:pep:`442` - Safe object finalization
@@ -416,9 +420,12 @@ weakref
416420
-------
417421

418422
New :class:`~weakref.WeakMethod` class simulates weak references to bound
419-
methods.
423+
methods. (Contributed by Antoine Pitrou in :issue:`14631`.)
420424

421-
(Contributed by Antoine Pitrou in :issue:`14631`.)
425+
New :class:`~weakref.finalize` class makes it possible to register a callback
426+
to be invoked when an object is garbage collected, without needing to
427+
carefully manage the lifecycle of the weak reference itself. (Contributed by
428+
Richard Oudkerk in :issue:`15528`)
422429

423430

424431
xml.etree

0 commit comments

Comments
 (0)