A function can be stored in a name and passed to another function. Passing the function gives the receiver behavior to call; adding parentheses calls it immediately. A higher-order function accepts a function, returns one, or both.
def cents_to_units(cents):
return cents / 100
def display_amount(value, convert):
return f"Amount: {convert(value):.2f}"
converter = cents_to_units
print(display_amount(425, converter))
print(display_amount(425, lambda cents: cents / 100))
Amount: 4.25
Amount: 4.25
display_amount calls convert with one argument. The lambda creates a function whose single expression is returned; use a named def when the behavior needs a clearer name or several statements. A callable is any value that can be called; a callback is a callable passed for another function to use. The expected arguments and return value are part of their agreement.
Composition passes one result to the next operation. The following factory returns a new function, rather than computing a result immediately:
def chain(first, second):
def run(value):
return second(first(value))
return run
def remove_spaces(text):
return text.strip()
def measure(text):
return len(text)
length_without_edges = chain(remove_spaces, measure)
print(length_without_edges(" kite "))
4
" kite " → remove_spaces → "kite" → measure → 4
first runs before second; its result must be an acceptable argument to second. Reversing them would pass an integer to remove_spaces, which expects text. Exceptions propagate unless handled. Chaining effectful functions does not make them pure; a direct expression may be clearer than a factory used only once.