New submission from Ryan Heisler <ryan.a.heis...@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@python
components: Documentation
messages: 385155
nosy: docs@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue42945>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to