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

Tim Peters report at bugs.python.org
Sat Jan 16 23:40:50 EST 2021


Tim Peters <tim at python.org> added the comment:

Not a problem. Arguments to a function are evaluated before the function is invoked.  So in

self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

self.name is evaluated before weakref.finalize is called(). `self.name` _extracts_ the `.name` attribute of `self`, and the result is simply a pathname (returned by the earlier call to `mkdtemp()`), from which `self` cannot be accessed.

Just like, e.g., for just about any old object O, after

    O.name = 42

a later `O.name` extracts the int 42, with no trace of that 42 had anything to do with `O`.

This isn't so when for a bound method object: `O.method_name` constructs and returns an object that _does_ reference `O`. That's why the earlier docs highlight bound method objects. For an attribute `name` bound to a chunk of data, `O.name` just retrieves that data, which _generally_ has nothing to do with `O` beyond that it happens to be reachable from `O` (but also generally NOT the reverse).

----------
nosy: +tim.peters

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


More information about the Python-bugs-list mailing list