[Python-Dev] PEP 442: Safe object finalization

Terry Jan Reedy tjreedy at udel.edu
Sat May 18 18:25:30 CEST 2013


On 5/18/2013 11:22 AM, Antoine Pitrou wrote:
> On Sat, 18 May 2013 15:52:56 +0100
> Richard Oudkerk <shibturn at gmail.com> wrote:

>> 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

An attribute reference that can fail should be wrapped with try-except.

>>
>>        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'

Though ignored, the bug is reported, hinting that you should fix it ;-).





More information about the Python-Dev mailing list