order that destructors get called?

Brendan Miller catphive at catphive.net
Thu Apr 8 00:08:14 CEST 2010

I'm used to C++ where destrcutors get called in reverse order of construction
like this:

    Foo foo;
    Bar bar;

    // calls Bar::~Bar()
    // calls Foo::~Foo()

I'm writing a ctypes wrapper for some native code, and I need to manage some
memory. I'm wrapping the memory in a python class that deletes the underlying
 memory when the python class's reference count hits zero.

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

Obviously, MyClass needs to hang onto a reference to delete_my_resource.

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.


More information about the Python-list mailing list