How soon after the reference count reaches zero is __del__
method called? Does the language promise that it's done right away, before any other use code can execute? Or can each implementation do what it likes, potentially delaying the call to __del__
arbitrarily long?
Please ignore the situation when the program is about to exit (I assume it means the last statement in the given block has finished, and the stack is empty). I understand that in such cases, there's no promises about __del__
; it may not even be called at all.
Also, I'm aware that reference count may be non-zero due to cycles, etc. I am not concerned about that here (I'm asking a separate question about it).
Python doesn't make any guarantees about when __del__
is called, or whether it is called at all. As it is, __del__
methods are unlikely to be called if the object is part of a reference cycle, because even if the cycle as a whole is cleaned up, Python has no way to decide where to break the cycle and in what order the __del__
methods (if any) should be called. Because of __del__
's rather quirky semantics (in order to call __del__
the refcount of the object is temporarily increased, and the __del__
method can prevent destruction of the object by storing the reference somewhere else) what happens in other implementations is a bit of a crapshoot. (I don't remember the exact details in current Jython, but it has changed a few times in the past.)
That said, in CPython, if __del__
is called, it's called as soon as the reference count drops to zero (since refcounting is the only way __del__
methods are called, and the only chance CPython has of calling __del__
is when the actual refcount is changed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With