[Python-Dev] PEP 442: Safe object finalization

Antoine Pitrou solipsis at pitrou.net
Sat May 18 17:22:02 CEST 2013


On Sat, 18 May 2013 15:52:56 +0100
Richard Oudkerk <shibturn at gmail.com> wrote:
> On 18/05/2013 3:18pm, Antoine Pitrou wrote:
> > 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.
> 
> So even more contrived:
> 
>       class Node:
>           def __init__(self, x):
>               self.x = x
>               self.next = None
>           def __del__(self):
>               print(self.x, self.next.x)
>               del self.x
> 
>       a = Node(1)
>       b = Node(2)
>       a.next = b
>       b.next = a
>       del a, b
>       gc.collect()

Indeed, there is an exception during destruction (which is ignored as
any exception raised from __del__):

$ ./python sbt.py 
1 2
Exception ignored in: <bound method Node.__del__ of <__main__.Node object at 0x7f543cf0bb50>>
Traceback (most recent call last):
  File "sbt.py", line 17, in __del__
    print(self.x, self.next.x)
AttributeError: 'Node' object has no attribute 'x'


The only reason this currently succeeds is that the objects end up in
gc.garbage, of course.

Regards

Antoine.




More information about the Python-Dev mailing list