Sub topic 2
Namespaces and scopes
This chapter assumes you can define and call functions, assign variables, use print, work with lists, and read a simple traceback. The previous chapter showed that a name is a label bound to an object. This chapter covers where those labels are stored and which part of a program can see them.
Two ideas that are easy to mix up
Two terms sound alike but describe different things.
- A namespace is a mapping from names to objects. It exists while the program runs. You can think of it as a dictionary.
- A scope is a region of the source code where a namespace is directly accessible. It is decided by where the code is written in the file.
A namespace answers "what is stored where?". A scope answers "which namespaces can this line of code see?". The Python documentation uses the terms this way, and the rest of the tutorial does too.
Namespaces are mappings
Each namespace holds name-to-object bindings. For the module-level namespace you can see this directly, because globals() returns the underlying dictionary.
language = "Python"
version = 3
ns = globals()
print(ns["language"])
print("version" in ns)
ns["extra"] = 99
print(extra)
# Output:
# Python
# True
# 99Writing to the dictionary created the name extra. Assigning with extra = 99 has the same effect. Writing to the module dictionary is fine for experiments, but it is rarely a good idea in real code.
Python has several kinds of namespace. They differ in when they are created and how long they live.
| Namespace | Created when | Lives until | Typical contents |
|---|---|---|---|
| Built-in | The interpreter starts | The interpreter exits | `len`, `print`, `ValueError` |
| Module (global) | The module is first imported or run | Normally the interpreter exits | Top-level assignments, `def`, `class`, `import` names |
| Function (local) | Each call to the function | The call returns | Parameters and names assigned in the body |
| Class body | The `class` statement executes | Becomes the class's attribute dictionary | Methods and class attributes |
Later chapters cover each row in detail. Here the goal is the shared model behind all of them.
The arrows show which namespace is consulted after another when a name is not found. The exact order is the LEGB rule, which gets its own chapter.
Every module has its own namespace
Each module has a separate global namespace. Two modules can both define x without conflict. The word "global" in Python means "global to this module", not "global to the whole program".
You reach another module's namespace through attribute access.
import math
print(math.__name__)
print("pi" in vars(math))
print(vars(math) is math.__dict__)
# Output:
# math
# True
# TrueThe expression math.pi looks up "pi" in the namespace of the math module. The same dot syntax reads attributes of any object, which is why modules, classes, and instances all behave like namespaces.
Every function call gets a fresh namespace
Python creates a new local namespace each time a function is called, not once when the function is defined. Parameters are the first names bound in it.
def area(width, height):
result = width * height
print(sorted(locals()))
return result
area(2, 3)
print("result" in globals())
# Output:
# ['height', 'result', 'width']
# Falselocals() shows the names in the call's namespace: both parameters and result. The name result is not in the module namespace, so the second line prints False.
Because each call starts fresh, local state does not carry over between calls.
def tally():
seen = []
seen.append(1)
return len(seen)
print(tally())
print(tally())
# Output:
# 1
# 1Each call builds a new seen list. The first call's list is discarded when the call returns. If you need state to survive between calls, you must keep it somewhere that outlives the call. Options include a module-level name, an object, or a closure, which a later chapter covers.
Scope is decided by where code is written
A scope is a textual region. Python decides which scope a piece of code belongs to by reading the source, before the code runs. This is called lexical (or static) scoping.
An assignment inside a def puts the name in that function's namespace. Code outside the function cannot see it.
def make_value():
y = 1
make_value()
print(y)
# NameError: name 'y' is not definedThe name y existed only in the namespace of that one call. After the call returned, the namespace was gone. The module scope never had a y to find.
Lexical scoping also means a function's view of names depends on where the function is defined, not where it is called. Here is an example.
def show():
print(label)
def run():
label = "run's label"
show()
label = "module label"
run()
# Output: module labelshow is written at module level, so its code can see the module namespace. The label assigned inside run is local to run. show never looks there, even though run calls it. Many learners expect the output to be run's label, so remember that calling code does not share its names with the function it calls.
Name lookup happens when the code runs
Scope decides which namespaces are searched for a name. The lookup itself happens at run time, each time the line executes. So a name used in a function body does not have to exist when the function is defined. It only has to exist when the function runs.
def greet():
return prefix + "world"
prefix = "hello, "
print(greet())
# Output: hello, worldprefix did not exist when def greet ran, but it exists by the time greet() is called. If you called greet() before the assignment, you would get a NameError.
Binding and lookup are separate events. Python decides at compile time which namespace a name belongs to. Which object the name holds is found only at run time. The chapter on assignment making a name local builds on this split.
Where the built-in namespace fits
The built-in namespace holds the names Python provides without any import, such as len, print, and ValueError. It is exposed through the builtins module.
import builtins
print(builtins.len is len)
print("ValueError" in dir(builtins))
# Output:
# True
# TrueBecause built-in names live in their own namespace, your own module namespace can reuse the same words. That is allowed, and it is also the source of the shadowing bugs covered in a later chapter.
Common mistakes at this level
- Treating "global" as program-wide. A global name belongs to one module. Another module needs
importor attribute access to reach it. - Expecting a function's locals to persist. Each call creates a new namespace, and the old one disappears when the call returns, unless a closure keeps it alive.
- Expecting the caller's names to be visible in the callee. Scope follows the written structure of the code, not the call chain.
- Assuming a name must exist at definition time. It only has to exist when the line using it runs.
Exercise
What does this program print, and why? def f(): value = "inside" value = "outside" f() print(value)
Show answer
It prints "outside". The assignment inside f binds value in the namespace created for that call of f. The module namespace holds a separate value, and the call did not change it.
Exercise
A script defines a function that reads the name rate, then calls that function, and only afterwards assigns rate = 0.5 at module level. Does the function call raise an error? What changes if the assignment is moved above the call?
Show answer
The call raises NameError, because lookup happens when the line runs and rate is not yet bound in the module namespace. If the assignment comes before the call, the function finds rate and works. The position of the def statement does not matter, only the order in which the assignment and the call execute.