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

Passing functions as parameters

Maybe assigning one function to a variable just to shorten the name is not for you, but this capability allows us to pass a function as a parameter to another function.

def call(func):
    return func(42)

def double(val):
    return 2 * val

def square(val):
    return val * val

if __name__ == "__main__":
    print(call(double))            # 84
    print(call(square))            # 1764
    print(call(lambda x: x // 2))  # 21
from passing_function import call, double, square

def test_call():
    assert double(3) == 6
    assert call(double) == 84

    assert square(2) == 4
    assert call(square) == 1764

TODO: prepare a more useful example!