Python Scope, Shadowing and global
The environment half of objective 4.2. Python resolves a name through four scopes - local, enclosing, global, built-in - and decides whether a name is local by looking for an assignment *anywhere* in the function, including below the line that reads it. That single rule produces UnboundLocalError, which is the most confusing error in the objective and completely predictable once you know what causes it.
Functions and Scope Guide 20 of 26 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 17 min
nonlocal arrived in Python 3.0 and is the one keyword here that Python 2 does not have. The UnboundLocalError message was reworded in Python 3.11 to name the variable; the behaviour is unchanged.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the environment half of the function objective. This matters because one assignment anywhere in a function makes that name local for the whole function - so a read on the first line can fail because of a line below it.
- reading a global, and shadowing one
- meeting the read that fails because of a line below it
- using
global, and its counterpartnonlocal - learning the four scopes Python searches, innermost first
- seeing that a local exists only while the call does
Before you start
-
Reading a global, and shadowing one
-
The read that fails because of a line below it
-
global: assign to the module-level name
-
nonlocal: assign to the enclosing function's name
-
The four scopes, innermost first
-
A local exists only while the call does
-
What the exam does with this objective