Course contentsShow
← Python
Lesson 607 of 1,06010. Advanced Language FeaturesFree lesson

Understanding First-Class Functions and Closures

Learn how functions can be passed as arguments and how closures capture local scope variables for later execution.

In this lesson, you will learn how functions in Python behave as objects and how closures allow functions to "remember" variables from their parent scope even after that scope has finished executing.

First-Class Functions

In Python, functions are "first-class citizens." This means they can be treated like any other variable: you can assign them to names, store them in data structures, and pass them as arguments to other functions. Because a function is just an object, you can pass my_function into another_function(my_function) and execute it inside that wrapper.

Understanding Closures

A closure occurs when a nested function captures and stores the state of its local environment. Even when the outer function finishes executing, the inner function retains access to the variables that were defined in the outer function’s scope.

Consider this example:

def make_multiplier(factor):
    # This inner function is a closure
    def multiplier(number):
        return number * factor
    return multiplier

# 'double' now holds the 'multiplier' function with 'factor' set to 2
double = make_multiplier(2)
print(double(5))  # Output: 10

In the code above, when make_multiplier(2) is called, it returns the multiplier function. Normally, the local variable factor would vanish once the outer function finishes. However, because multiplier references factor, Python creates a closure. The multiplier function "closes over" the value of factor and keeps it alive in its own environment. When we later call double(5), the function remembers that factor was 2.

This pattern is incredibly powerful because it allows you to create specialized functions on the fly without needing to create classes or global variables to maintain state. By leveraging closures, you can encapsulate data and logic together, keeping your code cleaner and more modular as your application grows in complexity.

Key Takeaway: Closures allow functions to capture and persist local variables from their outer scope, turning them into dynamic, stateful tools.