Recursive calls and stack

Terry Reedy tjreedy at udel.edu
Wed Feb 14 03:24:15 EST 2007


"jm.suresh at no.spam.gmail.com" <jm.suresh at gmail.com> wrote in message 
news:1171437825.977798.249420 at q2g2000cwa.googlegroups.com...
I am OK with calls being stacked, but I wondering will the local
variables be stacked given that return statement is followed by the
function call?

def test():
  x = 22
  y = 33
  z = x+y
  return anotherFunction(z)

In this function will all the local variables (x,y,z) be pushed into
the stack before calling anotherFunction(z) or Python will find out
that the locals are no longer needed as anotherFunction(z) is just
returned?
=================
To add to Gabriel's answer:

Questions of this sort are implementation specific.  CPython will allocate 
the objects on the heap.  But I believe at present something will go on the 
C stack with each function call.  I suspect that the C array that typically 
implements the local namespace is included but don't specifically know. 
The local names are deleted, and the associated heap objects released if 
that make the reference count 0, as part of the return process.  No 
optimization of the sort you indicate is done.  Indeed, the heap objects 
could have other references, and the namespace array is fixed size, so I am 
not sure there is anything that could, in general, be done.  In any case, 
Python never deletes without at least implicit instruction to do so.

The maximun recursion depth CPython will attempt is governed by an internal 
variable that you can get and set to adjust to your problem and hardware:

>>> sys.getrecursionlimit()
1000
>>> sys.setrecursionlimit(500)
>>> sys.getrecursionlimit()
500

Terry Jan Reedy







More information about the Python-list mailing list