Before seeing what a closure is, we have to first understand what nested functions and non-local variables are.
A function that is defined inside another function is known as a nested function. Nested functions are able to access variables of the enclosing scope.
In Python, these non-local variables can be accessed only within their scope and not outside their scope. This can be illustrated by the following example:
Closures are a powerful concept in programming that allows a function to access and manipulate the values of its enclosing function's variables even after the enclosing function has completed its execution. In Python, a closure is created when a nested function references a variable from its enclosing function's scope.
A closure is made up of two parts: the function object and the environment in which it was created. The environment consists of any variables that were in scope at the time the closure was created. When the closure is called, it has access to this environment and can use the values of the variables in its calculations.
Here's an example:
def outer_function(x): def inner_function(y): return x + y return inner_function closure = outer_function(10) print(closure(5)) # Output: 15
In this example, the outer_function
returns the inner_function
, which is a closure. When closure
is called with the argument 5
, it adds it to the value of x
(which is 10
) and returns the result 15
.
Closures are useful in situations where you want to create a function that can be configured with some initial state, and then reused multiple times without having to pass the same configuration values repeatedly. They are also used in advanced programming techniques such as decorators and generators.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.