Sub topic 4
Global names at module level
This chapter covers what a global name is in Python, where it lives, and how functions find it. It assumes you can define and call functions, use assignment and print, work with lists, and read a simple traceback. It does not cover the global statement. A later chapter handles that.
What "global" means in Python
A global name is a name bound at the top level of a module. A module is one .py file, and its top level is every statement that is not inside a def or a class body.
"Global" here means global to that one module. It does not mean visible to the whole program. If your program has ten files, it has ten separate sets of global names.
Which statements create global names
Any statement that binds a name at module level creates a global. Binding is not limited to =.
| Statement at module level | Name it binds |
|---|---|
| `x = 5` | `x` |
| `import math` | `math` |
| `from math import pi` | `pi` |
| `def area(r): ...` | `area` |
| `class Shape: ...` | `Shape` |
| `for index in range(3): ...` | `index` |
| `with open(path) as handle: ...` | `handle` |
The next script binds one name with each of several statement types. It then lists the module's own names.
import math
PI_ROUNDED = round(math.pi, 2)
def area(r):
return PI_ROUNDED * r * r
class Shape:
pass
for index in range(3):
pass
print(sorted(n for n in globals() if not n.startswith("__")))
# Output (when run as a script):
# ['PI_ROUNDED', 'Shape', 'area', 'index', 'math']The loop variable index is still there after the loop ends. The generator variable n is not in the list, because a generator expression has its own scope. Parameters and local variables inside area are also absent, because they exist only while the function runs.
Blocks do not create scopes
In Python, only functions, classes, comprehensions, and modules create scopes. Statements such as if, for, while, try, and with do not. A name bound inside one of those blocks at module level is a plain global.
if True:
message = "set inside an if block"
print(message)
# Output: set inside an if blockIf you come from a language with block scoping, this is a common surprise. It also means a loop variable leaks. After for index in range(3), the name index stays bound to 2.
There is one exception: the name in an except ... as clause. Python deletes it when the clause ends.
try:
int("x")
except ValueError as err:
pass
print(err)
# NameError: name 'err' is not definedIf you need the exception after the block, assign it to another name inside the except clause.
The module namespace is a dictionary
Each module's global names are stored in a dictionary. The built-in function globals() returns it. Keys are the names as strings and values are the objects they refer to.
answer = 42
print(globals()["answer"])
# Output: 42
globals()["other"] = "added through the dict"
print(other)
# Output: added through the dictThis explains several behaviors. Binding a global is a dictionary store. Looking one up is a dictionary read. Deleting one with del answer removes the key.
Writing to globals() is rarely a good idea in application code, because readers cannot find where other comes from. It is useful to know the mechanism, though. The same dictionary is visible as module.__dict__ from outside the module.
Python also puts a few names there automatically. The most useful are __name__, __file__, and __doc__. The value of __name__ is "__main__" when you run the file directly, and the module's import name when another file imports it. That is how the common if __name__ == "__main__": check works.
When module-level code runs
Module-level statements run once, from top to bottom, the first time the module is executed or imported. A def statement does not run the function body. It binds the name to a function object and moves on.
This ordering matters in two ways:
- A module-level statement can only use a global that an earlier statement already bound.
- A function body can use a global that is bound later in the file, as long as it is bound before the function is called.
The second point is easy to miss. Names inside a function are looked up when the function runs, not when it is defined.
def greet():
return PREFIX + " world"
PREFIX = "hello"
print(greet())
PREFIX = "goodbye"
print(greet())
# Output:
# hello world
# goodbye worldgreet was defined before PREFIX existed, and the code still works. The second call also sees the new value, because the function looks PREFIX up again each time it runs. If you called greet() before the line PREFIX = "hello", you would get NameError: name 'PREFIX' is not defined.
Reading a global from inside a function
A function can read a global without any special declaration. If the name is not found locally, Python looks in the module's global namespace.
count = 0
def read_count():
return count
print(read_count())
# Output: 0The key detail is that read_count never assigns to count. Reading works from any function. Assigning is where the rules change, and the chapter on why assignment makes a name local explains that. For now, treat reading as safe and assignment inside a function as something that creates a separate local name.
Keep in mind that a global read inside a function is a hidden input. Calling read_count() twice can give different results if some other code changes count in between. Functions that depend only on their arguments are easier to test.
One global namespace per module
Each module has its own globals() dictionary. Two modules can both define a name debug and the two do not interact. To share a value, one module imports the other.
The way you import decides what you share. Compare these two files.
# config.py
debug = False# main.py
import config
from config import debug
config.debug = True
print(config.debug)
print(debug)
# Output:
# True
# Falseimport config binds the name config to the module object. Writing config.debug = True changes the debug entry inside config's namespace, so every file that reads config.debug sees True.
from config import debug is different. It binds a new name debug in main.py's namespace to the object that config.debug referred to at that moment. That is the value False. Rebinding config.debug afterward does not update the copy in main.py.
When a value will change at run time, other modules should refer to it as config.debug. Copying it with from config import debug gives a snapshot.
Common errors
- Using a global before it is bound. Module-level code runs in order, so a name used on a line above its assignment raises
NameError. Function bodies are safe only if they are called after the binding. - Expecting block scope. Loop variables and names bound in
ifblocks remain after the block. Code that reuses a short name such asiat module level can overwrite or reuse an older value without warning. - Expecting a name to exist in another module.
NameErroris raised if you usehelperinb.pywhen it was defined only ina.py. Import it, or importaand writea.helper. - Stale
fromimports. A name copied withfrom module import namedoes not follow later rebinding in the source module. - Circular imports. If
a.pyimportsb.pyandb.pyimportsa.pyat module level, one of them can run before the other has finished binding its names. A common symptom isImportError: cannot import name ... (most likely due to a circular import). Moving the shared names to a third module avoids it.
Conventions for module-level names
Python does not enforce constants, but a common convention is UPPER_CASE for values that should never change, such as MAX_RETRIES = 3. Treat those as read-only. Keep mutable module-level state to a minimum. Each global that changes at run time is something every function in the module can depend on, and it makes bugs harder to trace.
The final chapter of this tutorial gives more advice on structuring code to avoid these problems.
Exercise
A file named settings.py contains level = 1. A second file runs from settings import level, then runs import settings, then runs settings.level = 5, and finally prints level and settings.level. What does it print, and why?
Show answer
It prints 1 and then 5. The from settings import level statement binds a separate name level in the second file's namespace to the object 1. The later assignment settings.level = 5 rebinds the entry in settings's own namespace, but the copied name level in the second file still refers to 1.
Exercise
What happens when this script runs, and which line causes it? def total(): return base + extra base = 10 print(total()) extra = 5
Show answer
It raises NameError: name 'extra' is not defined, raised from inside total on the print(total()) line. The function definition itself is fine, and base is already bound when total is called. But extra is not bound until the last line, which runs after the call. Moving extra = 5 above print(total()) fixes it.