Python Closures with Example
In this article, we are going to learn about Python closures and how to implement them with an example.
To understand closures we need to first understand nested functions and non-local variables.
Nested Functions
When we define a function inside another function then it is called as nested function.
def function_1(): msg = 'Meghana' def function_2(): msg = 'CodeSpeedy' print(msg) function_2() print(msg) function_1()
In the above example, function_2 is a nested function.
Output:
CodeSpeedy Meghana
Non-local variables
In the above example, instead of accessing the local variable msg in function_2 if we want to access the non-local variable, we can use the keyword nonlocal.
def function_1(): msg = 'Meghana' def function_2(): nonlocal msg msg = 'CodeSpeedy' print(msg) function_2() print(msg) function_1()
Here, we are accessing the nonlocal variable itself and no new local variable is created.
Output:
CodeSpeedy CodeSpeedy
Python Closures
In the case of nested functions, if we want to call the nested function function_2 we cannot call it directly from outside of function_1. For that purpose, we can use closures.
A closure is an object of a function that remembers the data in its enclosing scope. It is the process of binding data to a function without actually passing them as parameters to the function.
Let us look at the below example:
def function_1(): msg = 'Meghana' def function_2(): print(msg) return function_2 function_2_obj = function_1() function_2_obj()
Here, if we call function_2 from outside of function_1 we get an error because it is out of the scope of accessibility.
Instead, we can create a function object for function_2 by returning the function from function_1. This function object will hold the function along with the data in its enclosing scope. Even if we delete function_1, we can still access function_2 without any problem.
Output:
Meghana
Also, read more about nested functions and non-local variables at,
Implementation of nested function in Python
Scope of a variable, global and non-local keyword in python
Leave a Reply