Python Closures
1. What is a Closure
A closure is a function that remembers and has access to variables from its enclosing scope even after the outer function has finished execution.
def outer():
message = "Hello"
def inner():
return message
return inner
func = outer()
print(func()) # Output: HelloThe inner function retains access to message.
2. Basic Closure Structure
def multiplier(x):
def multiply(y):
return x * y
return multiply
times2 = multiplier(2)
print(times2(5)) # Output: 10Functions carry state without using global variables.
3. Closure Retaining State
Closure maintains persistent state across calls.
4. nonlocal in Closures
nonlocal allows modification of enclosed variables.
5. Closure vs Global Variable
Closures prevent unintended side-effects on global state.
6. Multiple Closures from Same Function
Each closure holds its own independent environment.
7. Inspecting Closure Variables
Shows internal structure of closure data.
8. Closures as Function Factories
Closures generate specialized functions dynamically.
9. Closure in Decorators (Foundation Pattern)
Decorators rely on closures to extend function behaviour.
10. Real-World Closure Example (Configuration)
Closures encapsulate configuration logic cleanly.
Last updated