Curriculum
In Python, a closure is a function object that has access to variables in its enclosing lexical scope, even after the enclosing function has finished executing. In other words, a closure “closes over” the environment in which it was created, so that it can access and modify variables that are not local to it. Closures are a powerful feature of Python that allow for more flexible and expressive code.
Here’s an example of a closure in Python:
def outer_function(x): def inner_function(y): return x + y return inner_function closure = outer_function(5) print(closure(3)) # 8
In this example, we define a function called outer_function
that takes one argument, x
. Inside outer_function
, we define another function called inner_function
that takes one argument, y
, and returns the sum of x
and y
. Finally, we return the inner_function
from outer_function
.
We then call outer_function
with the argument 5, which creates a closure containing the value of x
. We assign the resulting function object to the variable closure
.
We can then call the closure
function with the argument 3, which calls the inner_function
with x
set to 5 and y
set to 3, and returns the result 8.
Here’s another example of a closure that uses a mutable variable:
def counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment c1 = counter() print(c1()) # 1 print(c1()) # 2 c2 = counter() print(c2()) # 1
In this example, we define a function called counter
that creates a closure containing a mutable variable called count
. Inside counter
, we define another function called increment
that increments the count
variable and returns its new value.
We then create two instances of the counter
closure, c1
and c2
. Each instance has its own count
variable that is separate from the others.
When we call c1()
twice, it increments the count
variable within the closure and returns its new value, which starts at 1 and increases by 1 each time. When we call c2()
, it creates a new closure with its own count
variable that starts at 1.
Closures are useful when you want to create functions that have “state” or remember information from one call to the next. By closing over the environment in which they were created, closures can maintain their own internal state and behavior, making them a powerful and flexible tool in Python programming.