Closures

Anand VunnamAnand Vunnam
2 min read

Closure

A Closure is a Python function object that remembers values in enclosing scope even if they are not present in memory.

It is a record that stores a function together with an environment. It is like a mapping associating each variable of the function with a value or reference to which the name was bound when the closure was created.

Let us look at an example to understand it even better.

def outerfunc(text: str):
    def innerfunc():
        print("Hello,", text)
    return innerfunc

myfunc = outerfunc("Anand")
myfunc()

Output:

Hello, Anand

If we try to print the myfunc variable the result would look like this<function outer..inner at 0x7fad91df3910> which is a function object.

Now that we know what a closure in Python is, we will see why we need closures in real-time.

Why do we use closures?

  • Closures can be used to reduce or avoid the usage of global variables. Let's say, we only have one function that is using a global variable in that case we can use closure and this reduces the use of global data.

  • If there are very few functions in our code, it is good to use closures. However, if it has more functions, using OOPs would be appropriate.

  • The closure also provides a data-hiding feature, where the inner function implementation is hidden or we can say as the inner function can only be accessed via the outer function.

0
Subscribe to my newsletter

Read articles from Anand Vunnam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anand Vunnam
Anand Vunnam