0
0
PythonConceptBeginner · 3 min read

What is Closure in Python: Simple Explanation and Example

A 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

This example shows a function that creates a closure to remember a number and add it to another number later.
python
def make_adder(x):
    def adder(y):
        return x + y
    return adder

add_five = make_adder(5)
print(add_five(10))
Output
15
🎯

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.

Key Takeaways

A closure lets a function remember variables from its outer scope even after that scope ends.
Closures help keep data private and persistent without using global variables.
They are useful for creating customized functions and managing context in callbacks or decorators.