Skip to main content

Python Tutorial 5.6 - Closures in Python

Welcome to the “Closures” tutorial!


Overview

A closure captures variables from its enclosing scope.

Example

def make_multiplier(x):
    def multiplier(n):
        return x * n
    return multiplier

times3 = make_multiplier(3)
print(times3(5))  # 15
  • multiplier remembers x even after make_multiplier finishes.

Key Takeaways

  • Closures allow stateful functions without globals.
  • Useful for factory functions and callbacks.

Happy coding!

Comments