Python Closure

Sai Prabhanj Turaga
1 min readOct 1, 2023

--

In Python, a closure is a function object that has access to variables in its enclosing lexical scope, even when the function is called outside that scope. This allows a function to “remember” the environment in which it was created and access variables from that environment, even if those variables are no longer in scope when the function is called. Closures are a powerful and flexible feature in Python and are commonly used in functional programming.

Here’s a simple example to illustrate closures in Python:

In this example:

1. `outer_function` is the enclosing function that takes an argument `x`.
2. `inner_function` is defined within `outer_function` and is a closure because it has access to the `x` variable from its enclosing scope.
3. When `outer_function(10)` is called, it returns `inner_function`, creating a closure that “remembers” the value of `x` as 10.
4. Later, when `closure(5)` is called, it adds 5 to the `x` value stored in the closure, resulting in 15.

Closures are often used in Python for various purposes, such as creating function factories, decorators, and callback functions. They provide a way to encapsulate behavior and data, making code more modular and maintainable.

--

--

Sai Prabhanj Turaga
Sai Prabhanj Turaga

Written by Sai Prabhanj Turaga

Seasoned Senior Engineer, works with Data

No responses yet