Course contentsShow
← Python
Lesson 559 of 1,0609. Type Safety and Code QualityFree lesson

Implementing Callable Type Hints for Functions

You will learn how to annotate higher-order functions that accept other functions as arguments by specifying their signature and return types.

Implementing Callable Type Hints for Functions

In this lesson, you will learn how to use the Callable type hint to explicitly define the expected structure of functions passed as arguments to other functions.

The Need for Higher-Order Type Safety

When you write a function that accepts another function as an argument—often called a "higher-order function"—Python’s basic type hints aren't enough to tell your IDE or type checker exactly what that argument should look like. If you simply use func: object, the type checker has no idea if the passed function expects two integers, one string, or no arguments at all.

To solve this, we use Callable from the typing module. The syntax is Callable[[ArgType1, ArgType2], ReturnType].

Concrete Illustration

Imagine you have a function apply_operation that runs a calculation based on two numbers. You want to ensure the function passed into it accepts exactly two integers and returns an integer.

from typing import Callable

def apply_operation(x: int, y: int, operation: Callable[[int, int], int]) -> int:
    return operation(x, y)

def add(a: int, b: int) -> int:
    return a + b

# This is type-safe!
result = apply_operation(5, 3, add)

In this example, Callable[[int, int], int] tells the type checker: "The first argument must be a function that accepts two integers and returns an integer." If you tried to pass a function that only accepted one argument, your static analysis tool (like mypy) would flag it as an error before you even run the code.

Handling Functions with No Arguments

If the function you are passing requires no arguments, you represent the input list as an empty list: Callable[[], int]. This clarity prevents bugs where you might accidentally pass a function with the wrong signature, ensuring that your higher-order functions remain robust and predictable.

Key Takeaway: Use Callable[[ArgTypes], ReturnType] to enforce the specific signature of functions passed as arguments, ensuring your code remains predictable and catching mismatches during static analysis.