Generarl programming question.

Terry Reedy tjreedy at
Sat Apr 11 23:12:14 CEST 2015

On 4/11/2015 3:19 PM, Thomas 'PointedEars' Lahn wrote:
> Terry Reedy wrote:
>> On 4/11/2015 12:23 PM, Thomas 'PointedEars' Lahn wrote:
>>> Chris Angelico wrote:
>>>> The 'x' inside each function is completely separate, no matter how
>>>> many times they get called. They're usually stored on something called
>>>> a "call stack" - you put another sheet of paper on top of the stack
>>>> every time you call a function, local variables are all written on
>>>> that paper, and when you return from a function, you discard the top
>>>> sheet and see what's underneath.
>>> Thank you for that description; I shall use it from now on when teaching
>>> laymen about the call stack.
>> What Chris is describing is one local namespace (sheet of paper) per
>> function *call*.

> I *know* what he is describing: the *call* stack.

My comment above was directed not at you specifically but at the OP, 
Jonas, who appears to have had a mental model (like the following) in 
which recursion is not possible.  I think this mental model is fairly 
common among programming newbies.  And it is not crazy, just obsolete 
and superceded.  And, we constantly talk about a function's local names, 
which is correct, without constantly adding the caveat that in Python 
(and most modern languages) they are instanced per call.

I think of functions as being something like a class, in that each call 
gives a new instance with a new set of named values.

>> In early Fortran (at least the first version I used),
>> there was one local namespace (sheet) per *function*.
> The names in such namespaces are now called static variables.  AFAIK, Python
> does not have them, but PHP, for example, has:
>    function foo ()
>    {
>      static $bar = 1;
>      $bar *= 2;
>      return $bar;
>    }
> The variable $bar then keeps its last value for subsequent calls of foo().

In Python, one can do something similar with attributes, except that 
attributes are easily accessible from outside the function.  Mutable 
defaults probably come closer.

def doubler(_val=[1])"
   _val[0] *= 2
   return _val[0]

print(doubler(), doubler(), doubler())
# 2 4 8

>> The call stack was a stack of (pointers to) functions.
> It would appear that the commonly used definition of “call stack” has
> considerably changed since then, since I have been programming computers for
> more than two decades now (not including FORTRAN, though) and never heard of
> your definition before.

I don't know what the stack required for returns was called in Fortran 
or how it was implemented in any particular compiler.

>> It has been proposed that Python use a hybrid model.  Function objects
> Interesting.  I did not know that functions are objects in Python, too.

In Python, everything you can bind a name to is an object, and in 3.x, 
an instance of the base class 'object'.

Terry Jan Reedy

More information about the Python-list mailing list