Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Returning a closure

In this example the internally created function depends on a parameter the create_incrementer received. This parameter will go out of scope at the end of the create_incrementer function, but because it is used inside the internal function which was returned the caller, inside it will stay alive.

This is called a closure and it can be extremly useful in certain cases.

def create_incrementer(num):
    def inc(val):
        return num + val
    return inc

inc_5 = create_incrementer(5)
inc_7 = create_incrementer(7)

if __name__ == "__main__":
    print(inc_5(10))  # 15
    print(inc_5(0))   #  5

    print(inc_7(10))  # 17
    print(inc_7(0))   #  7
from incrementer import inc_5, inc_7

def test_inc_5():
    assert inc_5(1) == 6
    assert inc_5(-5) == 0

def test_inc_7():
    assert inc_7(1) == 8
    assert inc_7(-5) == 2