Sub topic 2
Namespaces and scopes
This chapter assumes you can define and call functions, use assignment and print, work with lists, and read a simple traceback. It builds on the idea that a name refers to an object. Here you learn where Python keeps those names.
What a namespace is
A namespace is a mapping from names to objects. You can picture it as a dictionary. The keys are names such as x or print, and the values are the objects those names refer to. Python keeps several namespaces at the same time, and each one is separate from the others.
The main kinds are:
| Namespace | Holds | Created | Discarded |
|---|---|---|---|
| Built-in | Names such as `print`, `len`, `list` | When the interpreter starts | When the interpreter exits |
| Global (module) | Names assigned at the top level of a file | When the module is loaded | Normally when the program ends |
| Local (function) | Parameters and names assigned in a function | Each time the function is called | When the call returns |
| Enclosing | Local names of an outer function | When the outer function is called | When no inner function still needs them |
What a scope is
A scope is a region of source code where a namespace is directly available. If you write a bare name such as x, the scope rules decide which namespace Python searches for it. A namespace exists while the program runs. A scope is a property of where you wrote the code.
Looking at namespaces
Two built-in functions show namespaces as dictionaries. globals() returns the module namespace, and locals() returns the current local namespace.
x = 10
def show():
y = 5
print(sorted(locals()))
show()
print("x" in globals())
# Output:
# ['y']
# TrueInside show, the local namespace holds only y. The name x lives in the module namespace, so it does not appear in locals() there.
A new namespace for every call
Each call to a function gets a fresh local namespace. Nothing is left over from an earlier call.
def counter():
n = 0
n += 1
return n
print(counter())
print(counter())
# Output:
# 1
# 1Both calls print 1. The second call does not see the n from the first call, because that namespace was discarded when the first call returned.
Modules have their own namespaces
Every module has its own global namespace. Importing a module binds the module's name in your namespace. The names the module defines stay in the module's namespace.
import math
print(math.pi)
print("pi" in vars(math))
print("pi" in globals())
# Output:
# 3.141592653589793
# True
# FalseThis is why two modules can both define a name like total without conflict. The dot in math.pi tells Python to look in the namespace of math.
How this connects to the next chapters
This chapter only established that several namespaces exist and that each has its own lifetime. The next chapters cover what each one means for your code and the order in which Python searches them.
Exercise
A function assigns total = 0 and then returns. You call the function a second time. Does the second call see the total from the first call? Explain using namespaces.
Show answer
No. Each call creates a new local namespace, and the namespace from the first call is discarded when that call returns. The second call starts with an empty local namespace, so it only sees a total that it assigns itself.
Exercise
After import math, why does "pi" in globals() give False while math.pi works?
Show answer
import math binds only the name math in your module's global namespace. The name pi lives in the separate namespace of the math module. The expression math.pi looks up pi in that module's namespace.