[Python-Dev] Deletion order when leaving a scope?

"Martin v. Löwis" martin at v.loewis.de
Fri Jan 19 04:10:23 CET 2007


Larry Hastings schrieb:
> I just ran a quickie experiment and determined: when leaving a scope,
> variables are deleted FIFO, aka in the same order they were created. 

Your experiment was apparently incomplete: Variables are *not* deleted
in the same order in which they are created:

py> class A:
...   def __init__(self, n):self.n = n
...   def __del__(self): print "Deleting", self.n
...
py> def f(x):
...   if x:
...     a = A("a")
...     b = A("b")
...   else:
...     b = A("b")
...     a = A("a")
...
py> f(0)
Deleting a
Deleting b

Here, it creates b first, then a (it's the else case), yet
deletes them in reverse order.

As others have pointed out, the deletion order is the one
indicated by the locals array:

py> f.func_code.co_varnames
('x', 'a', 'b')

Regards,
Martin


More information about the Python-Dev mailing list