order that destructors get called?
apt.shansen at gmail.invalid
Wed Apr 7 18:16:13 EDT 2010
On 2010-04-07 15:08:14 -0700, Brendan Miller said:
> When doing this, I noticed some odd behaviour. I had code like this:
> def delete_my_resource(res):
> # deletes res
> class MyClass(object):
> def __del__(self):
> o = MyClass()
> What happens is that as the program shuts down, delete_my_resource is released
> *before* o is released. So when __del__ get called, delete_my_resource is now
The first thing Python does when shutting down is go and set the
module-level value of any names to None; this may or may not cause
those objects which were previously named such to be destroyed,
depending on if it drops their reference count to 0.
So if you need to call something in __del__, be sure to save its
reference for later, so that when __del__ gets called, you can be sure
the things you need are still alive. Perhaps on MyClass, in its
__init__, or some such.
> What I'm wondering is if there's any documented order that reference counts
> get decremented when a module is released or when a program terminates.
> What I would expect is "reverse order of definition" but obviously that's not
> the case.
AFAIR, every top level name gets set to None first; this causes many
things to get recycled. There's no order beyond that, though.
Namespaces are dictionaries, and dictionaries are unordered. So you
can't really infer any sort of order to the destruction: if you need
something to be alive when a certain __del__ is called, you have to
keep a reference to it.
... p.s: change the ".invalid" to ".com" in email address to reply privately.
More information about the Python-list