[Python-Dev] PEP 442: Safe object finalization
Antoine Pitrou
solipsis at pitrou.net
Sat May 18 16:18:11 CEST 2013
On Sat, 18 May 2013 14:56:38 +0100
Richard Oudkerk <shibturn at gmail.com> wrote:
> On 18/05/2013 9:59am, Antoine Pitrou wrote:
> > This PEP proposes to turn CI disposal into the following sequence (new
> > steps are in bold):
> >
> > 1. Weakrefs to CI objects are cleared, and their callbacks called. At
> > this point, the objects are still safe to use.
> >
> > 2. **The finalizers of all CI objects are called.**
>
> How do you know that one of the finalizers will not do something which
> causes another to fail?
>
> Presumably the following would cause an AttributeError to be printed:
>
> class Node:
> def __init__(self):
> self.next = None
> def __del__(self):
> print(self, self.next)
> del self.next # break Node object
>
> a = Node()
> b = Node()
> a.next = b
> b.next = a
> del a, b
> gc.collect()
It works fine:
$ ./python sbt.py
<__main__.Node object at 0x7f3acbf8f400> <__main__.Node object at 0x7f3acbf8f878>
<__main__.Node object at 0x7f3acbf8f878> <__main__.Node object at 0x7f3acbf8f400>
The reason is that, when you execute "del self.next", this removes the
last reference to self.next and destroys it immediately.
In essence, you were expecting to see:
- enter a.__del__, destroy b
- leave a.__del__
- enter b.__del__ oops?
But what happens is:
- enter a.__del__, destroy b
- enter b.__del__
- leave b.__del__
- leave a.__del__
Regards
Antoine.
More information about the Python-Dev
mailing list