Chapter 7: Adding Variables to S-Calc

Variable Scope

Consider the following variables, and the function $f$.


In [11]:
x = 1
y = 2
def f():
    x = 3
    y = 4

What will happen when we call the function $f$... what will the values of x and y be after the function call?


In [12]:
f()
print(x, y)


1 2

So, how many variables are there?

Closures

To explore more complex variable bindings, we introduce the idea of a closure. A closure is a fuction that captures the bindings of variables.


In [19]:
x = 1
y = 2
def make_closure():
    x = 3
    y = 4
    def f():
        print(x, y)
    return f

In [20]:
c = make_closure()
c()


3 4

In [22]:
x, y


Out[22]:
(1, 2)

In [23]:
c()


3 4

In [1]:
x = 5
y = 13
def make_closure():
    x = 42
    y = 911
    def func():
        global x # sees the global value
        print(x, y)
        x += 1

    return func

In [ ]:
def make_closure():
    value = 0
    def get_next_value():
        nonlocal value
        value += 1
        return value
    return get_next_value