Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how soon is `__del__` called after reference count drops to zero?

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

like image 277
max Avatar asked Dec 02 '22 00:12

max


1 Answers

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

like image 102
Thomas Wouters Avatar answered Dec 04 '22 09:12

Thomas Wouters