Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Previously, we talked about Python closures when we discussed Python Decorators. Time to turn it up a notch.
In this Python Closure tutorial, we’ll learn about Python closures and how to define them. Moreover, we will learn nested functions and nonlocal variables used in Closures.
At last, we cover the benefits & examples of Python closure.
So, let’s start the Python Closure Tutorial.
What is Python Closure?
When we define a function inside of another, the inner function is said to be nested inside the outer one.
Common uses of Python closure:
- Keeping secrets: A part of the code is kept hidden so that the other part of the code doesn’t become a mess.
- Avoiding classes: It is the simplest way to save data without any requirement for extra setup.
- Remembers the past: Even after the original code or value is deleted, the closure remembers the value.
Let’s take an example.
>>> def outerfunc(x): def innerfunc(): print(x) innerfunc() >>> outerfunc(7)
Output
If you noticed, innerfunc could read the variable ‘x’, which is nonlocal to it. And if it must modify ‘x’, we declare that it’s nonlocal to innerfunc.
We do this the way we saw in our tutorial on Python Namespace and Variable Scope.
How can we define a Python Closure Function?
Now that we’ve revised a couple of topics, we can move on to Python 3 closure. Let’s define a closure.
>>> def outerfunc(x): def innerfunc(): print(x) return innerfunc #Return the object instead of calling the function >>> myfunc=outerfunc(7) >>> myfunc()
Output
The point to note here is that instead of calling innerfunc here, we returned it (the object).
Once we’ve defined outerfunc, we call it with the argument 7 and store it in the variable myfunc. Okay, we’ve finished executing outerfunc now.
So, when we call myfunc next, how does it remember that ‘x’ is 7?
This is the point here. A Python 3 closure is when some data gets attached to the code.
So, this value is remembered even when the variable goes out of scope or the function is removed from the namespace.
If we delete outerfunc, myfunc still gives us 7.
>>> del outerfunc >>> myfunc()
Output
So, we conclude that we have a Python closure when a nested function references a value in its enclosing scope.
These three conditions must be met:
1. We must have a nested function.
2. This nested function must refer to a variable nonlocal to it(a variable in the scope enclosing it).
3. The enclosing scope must return this function.
Benefits of Python Closure
While it seems like a very simple concept, a closure in Python 3 helps us in the following ways:
1. With Python closures, we don’t need to use global values. This is because they let us refer to nonlocal variables. A closure then provides some form of data hiding.
2. When we have only a few Python methods (usually, only one), we may use a Python 3 closure instead of implementing a class for that. This makes it easier on the programmer.
3. A closure lets us implement a Python decorator.
4. A closure lets us invoke a Python function outside its scope.
More Examples of Python Closure
Before we say goodbye for today, let’s take a couple more examples of closure in python.
>>> def outer(x): result=0 def inner(n): nonlocal result while n>0: result+=x*n n-=1 return result return inner >>> myfunc=outer(7) >>> myfunc(3)
Output
>>> myfunc=outer(3) >>> myfunc(3)
Output
In this example, we declare the result to be nonlocal, and we return it from the inner. And then, we return inner from outer. Time for another example.
>>> def outer(func):
def inner(msg):
func(msg)
return inner
>>> def sayhi(msg):
print(msg)
>>> myfunc=outer(sayhi)
>>> myfunc("Hello")
Output
Here, we passed a function object to the outer.
Python Interview Questions on Closures
1. What are closures in Python?
2. What are closures used for in Python?
3. What are the advantages and disadvantages of using closures in Python?
4. Give an example of a Python closure.
5. How does Python closure work?
Conclusion
A closure is a function that remembers the state of its enclosing scope even after that outer function has finished running. When the inner function uses variables defined outside but not global, Python stores them in a cell object tied to the inner function. This lets you build simple factories like make_multiplier(n) that return a new function multiplying inputs by n, without classes.
Closures keep data private and safe from external edits, yet make it available on each call. They pair well with decorators and callbacks, carrying context without global clutter.
Furthermore, if you have any queries, feel free to ask in the comments section.
