Why doesn't my finaliser run here?

Ben Finney ben+python at benfinney.id.au
Sun Sep 4 08:37:53 EDT 2016


Steve D'Aprano <steve+python at pearwood.info> writes:

> Why doesn't __del__ run here?

Short anser: because nothing has removed the reference to the instance.

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

This is a good example of why it helps to *never* call ‘__init__’ the
“constructor”. It isn't, because ‘__init__’ acts on an
already-constructed instance.

Hance, an exception raised from ‘__init__’ is not going to affect
whether the instance exists.

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


Right. The instance is constructed successfully (by ‘__new__’, the
constructor). It will be bound to ‘s’, creating a reference to the
instance.

The exception raised from the initialiser does not stop you from binding
the instance to a name. That binding succeeds; the reference remains.
Nothing has caused that reference to go away.

-- 
 \           “I know that we can never get rid of religion …. But that |
  `\   doesn’t mean I shouldn’t hate the lie of faith consistently and |
_o__)                     without apology.” —Paul Z. Myers, 2011-12-28 |
Ben Finney




More information about the Python-list mailing list