[Python-Dev] Deletion order when leaving a scope? (original) (raw)

Neil Toronto ntoronto at cs.byu.edu
Thu Jan 18 18:04:42 CET 2007


Thomas Wouters wrote:

On 1/18/07, Larry Hastings <larry at hastings.org_ _<mailto:larry at hastings.org>> wrote:

I just ran a quickie experiment and determined: when leaving a scope, variables are deleted FIFO, aka in the same order they were created. This surprised me; I'd expected them to be deleted LIFO, aka last first. Why is it thus? Is this behavior an important feature or an irrelevant side-effect? Please regard it as an irrelevant side-effect. If you want objects to be cleaned up in a particular order, you should enforce it by having one of them refer to the other. A great many details can affect the order in which variables are cleaned up, and that only decreases refcounts of the actual objects -- a great many other details can then affect the order in which any objects left with a 0 refcount are actually cleaned up. Even not counting the more complicated stuff like GC and funky del methods, just having 'import *' or a bare 'exec' in your function can change the order of DECREFs.

I imagine this would be important to someone expecting system resources to be cleaned up, closed, deallocated, or returned inside of del methods. Someone coming from C++ might expect LIFO behavior because common idioms like RAII (Resource Allocation Is Instantiation) don't work otherwise. A Java programmer wouldn't care, being used to cleaning up resources manually with a try...catch...finally.

I'm just putting a possible motivation on the concern. It happens that the Pythonic Way is also the Java Way in this area: don't expect any specific deletion order (don't even expect a guaranteed call to del), and manually clean up after yourself. As a warning, this has been the subject of a great many flame wars between C++ and Java programmers...

Neil



More information about the Python-Dev mailing list