07. Closures and Nonlocal Variables
A closure is a function that "remembers" variables from its enclosing scope even after that scope is gone.
Example of a Closure
def outer(msg):
def inner():
print(msg)
return inner
hello = outer("Hello")
hello()
Nonlocal Variables
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c()) # 1
print(c()) # 2
Practice Challenge
Write a closure power_raiser(n) that returns a function raising numbers to the power of n.
Wrap-Up
- Closures capture variables from their enclosing scope.
- Use
nonlocalto modify outer-scope variables.