Concepts·Certified Associate Python Programmer
Python Closures
PCAP objective 5.3 is define and use closures. A closure is a nested function that keeps a reference to a variable from the function that created it - so the inner function outlives the outer call and still remembers. The mechanism is visible in `__closure__`, and the trap is late binding: a closure remembers the *variable*, not the value it had when the closure was made.
Comprehensions and Lambdas Guide 22 of 25 Advanced
- Python3.14.4
- OSUbuntu 26.04 LTS
- pip25.1.1
- TimeAbout 16 min
- Reviewed23 August 2026
Written against the versions above. `nonlocal` is Python 3 only - Python 2 could read an enclosing variable but not rebind it. Closures themselves have existed since Python 2.2.
| 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 |
Before you start
- guide 20 - the E in LEGB is what a closure uses.
- guide 21 - the late-binding trap usually appears with lambdas.
-
A function that builds a function
-
Where the remembered value is kept
-
A closure that remembers between calls
-
Without nonlocal
-
The late-binding trap
-
A closure as a configured function
-
What the exam does with this objective