0Pricing
Python Academy · Lesson

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

  1. First-Class Functions
  2. Closures and Free Variables
  3. nonlocal and Mutable State
  4. Partial Functions
← Back to Python Academy