@@ -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
5555cleanup function to be called when an object is garbage collected.
5656This 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
5960Most programs should find that using one of these weak container types
6061or :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.
445449Finalizer 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
491496Unless 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
493498is 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
0 commit comments