What is Closure in Python: Simple Explanation and Example
closure in Python is a function that remembers values from its enclosing scope even after that scope has finished executing. It allows the inner function to access variables defined in the outer function, preserving their state.How It Works
Imagine you have a box (an outer function) that holds some items (variables). Inside this box, you have a smaller box (an inner function) that can see and use those items. When you take the smaller box out of the big box, it still remembers the items it saw inside, even though the big box is closed.
In Python, this happens when an inner function uses variables from its outer function. The inner function keeps a reference to those variables, creating a closure. This means the inner function can use those values later, even if the outer function has finished running.
Example
def make_adder(x): def adder(y): return x + y return adder add_five = make_adder(5) print(add_five(10))
When to Use
Closures are useful when you want to keep some data private and use it later without using global variables. For example, you can create customized functions on the fly, like adding a fixed number to any input.
They are also helpful in event handling, callbacks, and decorators where you want to remember some context or settings while running a function later.
Key Points
- A closure is an inner function that remembers variables from its outer function.
- It allows data to be kept private and persistent without global variables.
- Closures help create flexible and reusable code like customized functions.