Environment diagram

From CS 61A Wiki
Revision as of 21:40, 26 May 2014 by Axis (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jump to: navigation, search

An environment diagram is a visualization of the frames of a program and all the existing bindings.

Frame

A frame contains bindings, which map a name/variable to a value. A function call creates a new frame whose parent is the current frame.

The first frame is the global frame.

Environment

An environment consists of a sequence of frames. For example, in the following code:

x = 1
y = 2
def outer():
    x = 3
    y = 4
    def inner():
        x = 5
        y = 6
    return inner
outer()()

the sequence of frames that makes up the environment of inner is innerouterglobal. Here are the bindings in each frame:

frame x y
global 1 2
outer 3 4
inner 5 6

Variable lookup

A name evaluates to the value bound to that name in the earliest frame of the current environment in which that name is found. In other words, to lookup a name in an environment, start looking in the local frame, then in the parent frame (if it exists), until you get to the global frame. For example, in the following code:

x = 1
def outer():
    def inner():
        return x
    return inner
outer()()

in the body of inner, to lookup x, look in the local frame inner. Since it is not there, look in the parent frame outer. Since it is not there, look in the parent frame (the global frame) and find x = 1.

Sources

Resources