Overview
A function defined inside another one remembers the variables around it — the foundation of decorators and callbacks.
- Functions returning functions
- Captured variables
- nonlocal to update them
Short Course
An inner function keeps access to the outer function's variables even after
the outer function has returned. Use nonlocal to change them.
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hello = make_greeter("Hello")
hello("Ana") # 'Hello, Ana!' — greeting was remembered
Task
Write make_counter(start=0, step=1) that returns a function. Each call to
that function adds step to the count and returns the new value. Every
counter keeps its own count.
Test Suites
Pending
Stdout