An environment consists of a sequence of frames. Code is evaluated line by line in the environment. Starting in the global frame, users evaluate environments by binding values to variables and by evaluating function calls. Function calls will create local frames, in which the user evaluates the calls (like a mini environment) and returns to the global frame. One way to evaluate an environment is through environment diagrams.
In the following code, the sequence of frames that makes up the environment of
x = 1 y = 2 def outer(): x = 3 y = 4 def inner(): x = 5 y = 6 return inner outer()()
- The integer 1 is assigned to variable x.
- 2 is assigned to y.
- The variable outer points to a function.
- The interpreter moves down to
outer()(), and executes the function
- x and y are re-assigned to 3 and 4 respectively.
- The variable inner points to a function (do not execute this function yet!).
- "Return inner" indicates that
outer()returns the function
inner, now we execute what's left:
- x and y are re-assigned to 5, 6.
- Program terminates.
(Values assigned to variables)
(Functions assigned to variables)
(Function call creates new frame)
(First function evaluated, next frame created)