[New-bugs-announce] [issue42945] weakref.finalize documentation contradicts itself RE: finalizer callback or args referencing object

Ryan Heisler report at bugs.python.org
Sat Jan 16 23:12:18 EST 2021


New submission from Ryan Heisler <ryan.a.heisler at gmail.com>:

In the documentation for `weakref.finalize` (https://docs.python.org/3.9/library/weakref.html#weakref.finalize), it says:

"Note It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj."

However, at the bottom of the document, in the section called "Comparing finalizers with __del__() methods" (https://docs.python.org/3.8/library/weakref.html#comparing-finalizers-with-del-methods), the following code is part of an example of how to use `weakref.finalize`:

class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()
        self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

I believe this code violates the rule that func, args, and kwargs should not have a reference to obj. In the example, obj is the instance of TempDir, and one of the arguments to finalize's callback is an attribute of the same instance of TempDir.

I do not know how to fix this example code. I found it while trying to figure out how to use `weakref.finalize`.

----------
assignee: docs at python
components: Documentation
messages: 385155
nosy: docs at python, ryan.a.heisler
priority: normal
severity: normal
status: open
title: weakref.finalize documentation contradicts itself RE: finalizer callback or args referencing object
versions: Python 3.10, Python 3.6, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42945>
_______________________________________


More information about the New-bugs-announce mailing list