Why doesn't my finaliser run here?

Steve D'Aprano steve+python at pearwood.info
Sun Sep 4 08:20:01 EDT 2016


Here's a finaliser that runs:


class Spam(object):
    def __new__(cls):
        instance = object.__new__(cls)
        print("instance created successfully")
        return instance
    def __del__(self):
        print("deleting", repr(self))


An example:


py> s = Spam(); del s
instance created successfully
deleting <__main__.Spam object at 0xb7bf270c>



Why doesn't __del__ run here?


class Eggs(object):
    def __new__(cls):
        instance = object.__new__(cls)
        print("instance created successfully")
        return instance
    def __init__(self):
        print("self definitely exists:", self)
        raise Exception
    def __del__(self):
        print("deleting", repr(self))


And an example:


py> e = Eggs()
instance created successfully
self definitely exists: <__main__.Eggs object at 0xb7bf21ec>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __init__
Exception
py>





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list