What is Python closure?

Before moving on to closure, we first need to understand nested functions and non-local variables.

Take a look at the code snippet below:

def main():
message = "Hello World"
def inner_main():
print(message)
inner_main()
main()

Explanation

  • In line 1, we define the main() function.
  • In line 2, we define a variable that is local to the function main().
  • In line 4, we define the nested functiona function inside a function inner_main(). This nested function is able to access the message that is not local to this function.
  • In line 7, we call the inner_main() function in our main() function.
  • Finally on line 9, we call the main() function and see the output as Hello World. This confirms that nested functions can access the local variables of the outer functions.

Closure in Python

Now that we understand how nested functions work, we can understand the concept of closure. In line 7 in the code above, instead of calling the nested function, what would happen if we return the closure() function?

Look at the code snippet below to understand this:

def main():
message = "Hello World"
def inner_main():
print(message)
return inner_main
closure = main()
closure()

Explanation

  • The code is the same until line 6.
  • In line 7, we return the nested function instead of calling it.
  • In line 9, we call the main() function. Here, the returned function from main() gets bound to the name closure.
  • Since main() returned a function, we can call closure(), and get the result from the nested function.

Hence, we can define closure as a function object that can remember the value in its scopes, even if they are not present in the memory.

This also means that you could delete the main() function from memory and access the returned function.

Take a look at the code snippet below to understand better.

def main():
message = "Hello World"
def inner_main():
print(message)
return inner_main
closure = main()
del main
closure()

Explanation

  • As seen in line 10, we deleted the main() function from the program memory, but we can still access the returned function. This is what closureThe value in the enclosing scope is remembered when the function is deleted from the memory or the variable goes out of scope. is!

When should closure be used?

This is a very tricky question as introducing too many nested functions can increase the complexity of the code. So, it is suggested to use closures when:

  • You want some kind of data hiding.
  • You want to reduce the usage of global variables.
  • You have fewer functions and attributes. In this case, it is efficient to use closure, but if you have many functions and attributes, it is advisable to use classes.