Closure

Python closures are used when inner functions are enclosed within the outer function, or in other words, when a nested function references a value in its enclosing scope. Closures can avoid the use of global values.

It is good to use them when you have to implement a few methods but their number is not enough to create a class, so closure will provide a more readable solution. But when the number of attributes and methods gets larger, it's better to implement a class.

Let's consider some examples:

def calculate_taxes(percentage):
    def taxes(sum_of_money):
        return sum_of_money * percentage / 100
    return taxes

# Taxes — 5%
taxes_5 = calculate_taxes(5)

# Taxes — 10%
taxes_10 = calculate_taxes(10)

print(taxes_5(1000))            # 50.0
print(taxes_5(4000))            # 200.0
print(taxes_5(6500))            # 325.0

print(taxes_10(1000))           # 100.0
print(taxes_10(4000))           # 400.0
print(taxes_10(6500))           # 650.0

This example shows that if we know that we need to calculate 5% or 10% of taxes from different amounts several times, then we can write this percentage once using a closure and use it many times.