Loading section...

Closures

A closure is a function that remembers variables from the scope where it was created, even after that scope has finished executing. This powerful pattern lets you create customized functions and maintain state between calls without using global variables or classes. Creating a Closure When a nested function references a variable from its enclosing function and is returned, Python creates a closure that captures that variable: How Closures Work When you call make_multiplier(2), Python creates a new multiply function with factor=2 attached. This attachment is the closure. When you later call double(5), the multiply function looks up factor in its closure and finds 2. Function Factory Pattern Closures enable the function factory pattern, where one function creates and returns customized versi