Back
+15 XP
Concept

Function Closures: Retaining Enclosed State

A closure occurs when an inner function remembers and accesses variables from its enclosing lexical scope, even after the outer function has finished executing 🎒.

python
def make_multiplier(factor):
    def multiply(n):
        return n * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))  # 10 🚀
print(triple(5))  # 15 âš¡

# 33. Function Closures: Retaining Enclosed State A closure occurs when an inner function remembers and accesses variables from its enclosing lexical scope, even after the outer function has finished executing 🎒. ```python def make_multiplier(factor): def multiply(n): return n * factor return multiply double = make_multiplier(2) triple = make_multiplier(3) print(double(5)) # 10 🚀 print(triple(5)) # 15 ⚡ ``` Even though `make_multiplier` exited, the returned `double` retains `factor = 2` in its secret `__closure__` cell. This lets you encapsulate state without writing full classes! 🎒 --- ### Question Where does Python store the closed-over variables of a closure function? 🧠 - [ ] a. In the function object's `__closure__` attribute cell tuple 🎒 - [ ] b. In a hidden temporary file inside `/tmp/python_closures` - [ ] c. Inside `sys.modules['__main__']` global state - [ ] d. In CPU register L1 cache directly --- ### Challenge Define `make_prefixer(prefix)` returning an inner function `prefixer(word)` that returns `f'{prefix}_{word}'`. Create `p = make_prefixer('API')`, print `p('USERS')` and `p('LOGS')`. 🎯 <details> <summary>Solution</summary> ```python def make_prefixer(prefix): def prefixer(word): return f"{prefix}_{word}" return prefixer p = make_prefixer("API") print(p("USERS")) print(p("LOGS")) ``` </details>

Checkpoint

Where does Python store the closed-over variables of a closure function? 🧠

Practice

Define `make_prefixer(prefix)` returning an inner function `prefixer(word)` that returns `f'{prefix}_{word}'`. Create `p = make_prefixer('API')`, print `p('USERS')` and `p('LOGS')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks