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

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

7

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

7

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

7

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:

  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 python3 helps us in the following ways:

  1. 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.
  2. 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.
  3. A closure, lets us implement a Python decorator.
  4. 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

42
>>> myfunc=outer(3)
>>> myfunc(3)

Output

18

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

Hello

Here, we passed a function object to 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 Python closure.
  5. 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

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

2 Responses

  1. Jatin says:

    the code under 5. is broken

Leave a Reply

Your email address will not be published. Required fields are marked *