Nested functions, how do they work (stack related)

Marko Rauhamaa marko at pacujo.net
Tue Dec 13 05:46:51 EST 2016


Veek M <vek.m1234 at gmail.com>:

> https://en.wikipedia.org/wiki/Call_stack
>
> 'Programming languages that support nested subroutines also have a field 
> in the call frame that points to the stack frame of the latest 
> activation of the procedure that most closely encapsulates the callee, 
> i.e. the immediate scope of the callee. This is called an access link or 
> static link (as it keeps track of static nesting during dynamic and 
> recursive calls) and provides the routine (as well as any other routines 
> it may invoke) access to the local data of its encapsulating routines at 
> every nesting level. 
>
> Some architectures, compilers, or optimization cases store one link for 
> each enclosing level (not just the immediately enclosing), so that 
> deeply nested routines that access shallow data do not have to traverse 
> several links; this strategy is often called a "display".'
>
> 1. What is the difference between a 'call frame' and a 'stack frame' in 
> the above context?

There's no difference.

> 2. He's saying that within the 'call frame' (whatever that is) there's 
> an address to one of the previous stack frames of the wrapper function ? 
> What does all that mean in terms of nested functions? Access link? How 
> are nested function stacks setup..

The classic C stack frame contains two addresses (in addition to the
arguments and local variables):

 * the return address in the calling function

 * the frame pointer in the calling function

Some languages (notably Pascal) add a third address:

 * the frame pointer in the outer function

Often, the outer function is the same as the calling function. However,
if the inner functions call each other, the outer function may be
further up the stack. Since the outer function's local variables are
seen by the inner functions, the extra pointer is needed to access them
directly.

Python has nested functions. Thus, the same technique can be used to
implement Python's internal call stack.

> 3. What exactly is a traceback object

It is an object that reports details of the call stack. It is mostly
useful for troubleshooting.

> How exactly does an exception fit in with tracebacks? How does all this 
> fit in with nested functions?

Well, the traceback object contains also the exception since it is
essential for troubleshooting.

> 4. When you call a nested function (decorator), it generally returns a 
> wrapper function but I thought he was just returning a reference to a 
> function object but obviously since it can see it's environment, how is 
> the stack being setup?

Now I don't exactly understand your question.


Marko



More information about the Python-list mailing list