Python Closure Tutorial – How to Define Python Closures Function
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Previously, we talked about Python closure, 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 function and nonlocal variables used in Closures.
At last, we cover 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. 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 Python Closure Function?
Now that we’ve revised a couple topics, we can move on to Python3 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 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 Python3 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 Python closure when a nested function references a value in its enclosing scope.
These three conditions must be met:
- We must have a nested function.
- This nested function must refer to a variable nonlocal to it(a variable in the scope enclosing it).
- The enclosing scope must return this function.
Benefits of Python Closure
While it seems like a very simple concept, a closure in python3 helps us in the following ways:
- With Python closure, 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.
- When we have only a few Python methods (usually, only one), we may use a Python3 closure instead of implementing a class for that. This makes it easier on the programmer.
- A closure, lets us implement a Python decorator.
- A closure lets us invoke 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 result to be nonlocal, and we return it from 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 outer.
Python Interview Questions on Closures
- What are closures in Python?
- What are closures used for in Python?
- What are the advantages and disadvantages of using closures in Python?
- Give an example of Python closure.
- How Python closure works?
Conclusion
With this last example, we conclude this Python closure tutorial with example. Indeed, Python closures are cool.
They let us refer to nonlocal variables, in turn helping with data hiding. We can also use them instead of classes when we only need about a couple methods.
Furthermore, if you feel any query, feel free to ask in a comment section.
You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google
the code under 5. is broken
Thanks for correcting us. We have done the changes.