Order of constructor/destructor invocation

Tim Legant tim-dated-1015967204.ddf39d at catseye.net
Tue Mar 5 16:06:43 EST 2002


"Reginald B. Charney" <news at charneyday.com> writes:

> Brett is exactly right. I am using an approach that is valid and elegant in
> C++. Since I am fairly new to Python, I had assumed it handled
> contructors/destructors in an ordered (i.e. deterministic) fashion. It seems
> not.

Sometimes valid and elegant in C++.  Specifically, valid and elegant
with objects allocated on the stack.  But Python objects are analogous
to C++ objects allocated on the heap.  If you have a pointer to an
object allocated on the heap in C++ and it goes out of scope, you've
just leaked memory.  Hardly valid and elegant. <wink>

Try explicitly deleting the Python objects.  I don't know if
destructor order is even guaranteed in that case or not, but you'll be
a lot closer to the C++ model, where you must explicitly delete heap
objects.  Despite the fact that the language hides the direct pointer
manipulation, Python objects, like Java objects, have pointer
semantics.

Oh.  And even if it does work, don't do it that way.  I agree with the
rest of the responses you've received: it's much better to be explicit
about cleanup.  If you have to call 'del' to cause your cleanup code
to execute, might as well call 'cleanup' or 'write_close' and let
Python worry about the 'del'.


Tim




More information about the Python-list mailing list