Python Closures

A closure is an inner function that remembers the values of the variables of its outer function, even after the outer function has finished running. To understand it, first learn what a nested function is.


Nested function

A function defined inside another function is a nested (inner) function. It can read the variables of the outer function.

def outer(text):
    def inner():
        print(text)

    inner()

outer("Hello")
Output of the above program is

Hello


Closure

Now the outer function returns the inner function without calling it (no brackets after inner). We call the returned function later, outside of outer().

def outer(text):
    def inner():
        print(text)

    return inner

my_func = outer("Hello")
my_func()
Output of the above program is

Hello

The outer() function is finished, but my_func still remembers text. That memory is the closure.


Closure with nonlocal

An inner function can read outer variables, but to change one, you must declare it with the nonlocal keyword. Without it Python thinks you are making a new local variable and raises an UnboundLocalError.

def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

c1 = make_counter()
print(c1())
print(c1())
print(c1())

c2 = make_counter()
print(c2())
Output of the above program is

1
2
3
1

Each call of make_counter() makes a new closure with its own count, so c2 starts again from 1.


Function factory

Closures are good to create many similar functions.

def make_greeting(greeting):
    def say(name):
        print(greeting + ", " + name)
    return say

hello = make_greeting("Hello")
namaste = make_greeting("Namaste")

hello("Robin")
namaste("Maria")
Output of the above program is

Hello, Robin
Namaste, Maria


When to use closures

  • To keep some data private without writing a class.
  • To create small custom functions, like the greeting example.
  • They are the base of decorators.

Summary


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.