[New-bugs-announce] [issue15528] Better support for finalization with weakrefs

Richard Oudkerk report at bugs.python.org
Wed Aug 1 18:18:47 CEST 2012


New submission from Richard Oudkerk:

A patch with docs and tests for the idea I suggested on python-ideas:

    http://comments.gmane.org/gmane.comp.python.ideas/15863

To repeat what I wrote there, the current issues with weakref callbacks include:

1. They are rather low level, and working out how to use them
   correctly requires a bit of head scratching.  One must find
   somewhere to store the weakref till after the referent is dead, and
   without accidentally keeping the referent alive.  Then one must
   ensure that the callback frees the weakref (without leaving any
   remnant ref-cycles).

   When it is an option, using a __del__ method is far less hassle.

2. Callbacks invoked during interpreter shutdown are troublesome.  For
   instance they can throw exceptions because module globals have been
   replaced by None.

3. Sometimes you want the callback to be called at program exit even
   if the referent is still alive.

4. Exceptions thrown in callbacks do not produce a traceback.  This
   can make debugging rather awkward.  (Maybe this is because printing
   tracebacks is problematic during interpreter shutdown?)

(Note that problems 2-4 also apply to using __del__ methods.)

Trivial usage of the class looks like

    >>> class Kenny: pass
    ...
    >>> kenny = Kenny()
    >>> finalize(kenny, print, "you killed kenny!")
    <finalize.finalize object at 0xffed4f2c>
    >>> del kenny
    you killed kenny!

----------
files: finalize.patch
keywords: patch
messages: 167142
nosy: sbt
priority: normal
severity: normal
stage: patch review
status: open
title: Better support for finalization with weakrefs
type: enhancement
versions: Python 3.4
Added file: http://bugs.python.org/file26649/finalize.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15528>
_______________________________________


More information about the New-bugs-announce mailing list