Change language

Closing Python

| |

Before seeing what closure is, we must first understand what nested functions and non-local variables are.

Nested functions in Python

A function that is defined inside another function is called a nested function. Nested functions can access environment variables. 
In Python, these non-local variables can only be accessed within their scope, not outside of it. This can be illustrated with the following example:

# Python program for illustration
# nested functions

def outerFunction (text):

text = text


def innerFunction ():

print (text)


innerFunction ()


if __ name__ = = ’__main__’ :

  outerFunction ( ’ Hey! ’ )

As we can see, innerFunction () can be easily accessed inside the body of externalFunction, but not outside its body. Hence, here, innerFunction () is treated as a nested function that uses text as a non-local variable.

Close Python

Closing — it is a functional object that remembers the values ​​in nested scopes, even if they are not in memory.

  • This is the entry that stores the function along with the environment: a mapping that binds each free function variable (variables that are used locally, but defined in a nested scope) with the value or reference to which the name was bound when closing was created.
  • Closure — as opposed to the simple function — allows functions to access these captured variables through copies of their values ​​or closure references, even if the function is called outside of their scope.

# Python program for illustration
# closure

def outerFunction (text):

  text = text


def innerFunction ():

print (text)


  return innerFunction # Note that we are returning a function without parentheses


if __ name__ = = ’__main__’ :

myFunction = outerFunction ( ’Hey!’ )

myFunction ()

 Output: omkarpathak @ omkarpathak-Inspiron-3542: ~ / Documents / Python-Programs / $ python Hey! 
  1. As you can see from the above code, closures help to call functions outside of their scope.
  2. The innerFunction function is only scoped inside an externalFunction. But with closures, we can easily extend its scope to call a function outside of its scope.

# Python program for illustration
# closing

import logging

logging.basicConfig (filename = ’example. log’ , level = logging.INFO)



def logger (func):

def log_func ( * args): (

’Running" {} "with arguments {}’ . format (func .__ name__, args))

  print (func ( * args))

# Needed to close the job (return without parentheses)

return log_func 


def add ( x, y):

return x + y


def sub (x, y):

return x - y


add_logger = logger (add)

sub_logger = logger (sub)


add_logger ( 3 , 3 )

add_logger ( 4 , 5 )

< code class = "undefined spaces">  

sub_logger ( 10 , 5 )

sub_logger ( 20 , 10 )

 OUTPUT: omkarpathak @ omkarpathak-Inspiron- 3542: ~ / Documents / Python-Programs / $ python 6 9 5 10 

When and why to use closures:

  1. Since closures are used as callback functions, they provide a kind of data hiding. This helps us reduce the use of globals.
  2. When there are few functions in our code, closures are efficient. But if we need to have a lot of features, then let’s go to the (OOP) class.

This article is provided by Omkar Pathak . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method