Scopes in Python

Ka-Ping Yee, 2005-11-29
Computer programs are full of names. There are names for functions, names for variables, and so on. When a name appears, it either defines the meaning of the name or refers to a definition elsewhere. The scope of a definition is the part of the program over which the definition holds. Every programming language has its own rules for determining scope.

For example, in the following bit of Python, the second line refers to the x that was defined on the first line.

x = 2 + 2
print 'two plus two is', x
Example 1. Simplicity itself.

Pretty simple, right? The scoping rules in Python are straightforward, and it's important to understand them well.

There are three main things to remember.

1. All Names are Scoped the Same

The first principle to know about Python is that names for all kinds of things — numbers, strings, functions, types, modules — are treated the same way. (This may be unlike other languages you've encountered; for example, in Java and C++, the variable blerg and the class blerg are considered two different things.) In Python, a name can only refer to one thing at a time.

Another way of looking at this is to say that all names are variables. Here's a program to illustrate this:

spoon = 2 + 2

print spoon

def spoon(x):
    return x + 3

print spoon

spoon = 'foo'

print spoon
Example 2. There is only one spoon.
Write down what you think each of the three print statements will print. Then start Python and type in the lines in the above example, one by one. Compare the results to what you predicted before proceeding.