I'm a bit confused what is happening to objects when Python interpreter shuts down. If I write a little code like that
class MyClass(object):
def __del__(self):
print "I'm going away"
o = MyClass()
and run it, I'll get this
I'm going away
My understanding is that when interpreter shuts down it will delete all references to created objects and these objects will run __del__()
if specified (because ref count for them is 0).
My confusion is because:
__del__()
I see this It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.
And it's getting a bit more complicated, are they saying that it's not guaranteed to be run because of some cycle dependancies or it's just not guaranteed? Who decides that?So my questions are:
__del__
in my example aboveguaranteed
to be called when I don't have reference cyclesI don't see the point of the first question, but for CPython 2.7.8, __del__
is called by PyInstanceObject.instance_dealloc
, which is registered as the tp_dealloc
, which is called when Py_DECREF
is called and the reference count reaches zero. So, let's just say the interpreter calls it, not Python code. If you're asking that question with the hope that you can change how or when it gets called, I don't think it's possible.
As to why it's not guaranteed, to do that you'd have to go through all modules deleting their variables before exit, but if the __del__
methods rely on any global variables, there's no simple way to guarantee a safe order for them to be executed. I'm not saying it's impossible, like with reference cycles, I'm saying it's complicated.
I imagine this was discussed at some point but the community or the BDFL decided it wasn't worth the hassle. I believe I saw some discussion about this years ago, but I couldn't find it now. Use of the __del__
method was never encouraged in the first place, and if you need to guarantee some destructor method is called, you might be better using context managers for that.
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