Sep 23

Lecture Overview

Names, namespaces, local vs global variables, function calling. For more, see the execution model.

Data Values and Variables

L = [1, 5, 12]
abc = L
abc.append(22)
print(L)
x = 12
y = x

Namespaces

Function Call and Scope

When functions are called, a new namespace is created. This namespace lives until the file returns, at which point the namespace is discarded. Before the start of execution of the body of the function, entries (name, address pairs) for the parameters are added to the namespace.

def somefunction(x):
    print(x + 5)

somefunction(12 + 22)

Here, 12 + 22 will be executed to a data value (holding 34) and then a namespace entry of x and the address of this data value is created. This is so that when print(x + 5) is executed, python will lookup x in the namespace and find the address of this value holding 34. At the end of a function, these namespace entries are discarded. So this namespace entry for x which was created at the start of the function is removed at the end of the function. We call this the scope of x.

The scope of a variable is the region of the code (think which line numbers) for which the variable is part of the namespace. We would say the variable x has scope the body of the function somefunction, meaning that the variable x is accessible only during the body of the function. Note that when the entry for x is discarded, the data value holding 34 can no longer be referenced by any entry in a namespace and so is garbage and will be collected (marked as unused) during the next garbage collection.

Local versus Global variables

Variables which are assigned to during the body of a function are called local variables, and are also discarded at the end of the function.

def somefunction(x):
    y = x + 4
    print(y - 2)

z = 44
somefunction(z - 6)

Exercises

No homework for today, I will show some examples of the above next time and then have some homework problems.