Closures and Free Variables
Capture state in inner functions.
Nested functions
Python lets you define a function inside another function. The inner function is created fresh each time the outer one runs.
def outer():
def inner():
return 'from inner'
return inner()
print(outer())Inner sees outer variables
An inner function can read variables defined in the enclosing function. These are called free variables because they are not local to the inner function.
def outer():
message = 'hello'
def inner():
return message
return inner()
print(outer())All lessons in this course
- First-Class Functions
- Closures and Free Variables
- nonlocal and Mutable State
- Partial Functions