In this lesson, you will learn how to use the Callable type hint to explicitly define the expected signatures of callback functions passed into higher-order functions.
Why Callable Signatures Matter
A "higher-order function" is a function that accepts another function as an argument. While basic type hints tell us that an argument is a function, Callable allows us to define exactly what that function looks like. Without this, static type checkers (like Mypy) cannot warn you if you pass a function that takes the wrong number of arguments or returns an incompatible type.
Defining the Signature
To document these callbacks, we use the Callable type hint from the typing module. The syntax is Callable[[ArgType1, ArgType2, ...], ReturnType].
Consider a scenario where you have a function that processes a list using a custom transformation:
from typing import Callable
# We define a function that expects a callback
# The callback must take an int and return a str
def transform_data(data: list[int], formatter: Callable[[int], str]) -> list[str]:
return [formatter(item) for item in data]
# A valid callback
def to_currency(amount: int) -> str:
return f"${amount}.00"
# Usage
results = transform_data([10, 20, 30], to_currency)
Preventing Type Mismatches
If you were to accidentally pass a function that requires two arguments instead of one, or one that returns an int instead of a str, your static type checker would flag the mismatch immediately. This acts as a contract between the higher-order function and the logic being injected into it.
If your callback doesn't take any arguments, you simply pass an empty list: Callable[[], None]. If you have a complex signature, you can even use a TypeAlias to keep your code readable:
from typing import Callable, TypeAlias
# Defining a cleaner alias for the signature
PriceFormatter: TypeAlias = Callable[[int], str]
def process_prices(prices: list[int], callback: PriceFormatter) -> list[str]:
return [callback(p) for p in prices]
By explicitly defining these signatures, you ensure that your code remains predictable and robust, even as your logic grows more complex.
Key Takeaway: Use Callable[[InputTypes], ReturnType] to define the precise input and output requirements for functions passed as arguments, ensuring compile-time safety and clearer documentation for your higher-order functions.