In this lesson, you will learn how to use the @overload decorator to inform static type checkers about precise input-output relationships that a single function signature cannot express.
The Limitation of Simple Unions
Sometimes, a function behaves differently depending on the input type. For example, consider a function that processes an input and returns a value of the same type. If you use a simple Union type, you lose specificity:
from typing import Union
def process(value: Union[int, str]) -> Union[int, str]:
return value
If you pass an int to this function, a type checker like mypy only knows that the result is Union[int, str]. It doesn't "know" that an int input guarantees an int output.
Using @overload
To solve this, we define multiple "fake" signatures using @overload to describe these specific paths to the type checker. We then provide a single, permissive "implementation" signature that handles the actual runtime logic.
from typing import overload, Union
@overload
def process(value: int) -> int: ...
@overload
def process(value: str) -> str: ...
def process(value: Union[int, str]) -> Union[int, str]:
# This is the actual runtime implementation
return value
How it Works
- The Overloads: The lines decorated with
@overloadare strictly for the static type checker. They describe the valid ways the function can be called. Notice they end in...instead of a function body. - The Implementation: The final function definition (without the decorator) contains the actual code. This signature must be broad enough to encompass all the overloads, but it is effectively hidden from the user because the type checker uses the
@overloadsignatures to determine the return type during development.
By using this pattern, if you call process(10), the type checker now understands the return value is definitively an int. This provides much stricter type safety without duplicating your runtime logic.
Key Takeaway: Use @overload to define specific input-to-output mapping rules for static analysis while maintaining a single, clean runtime implementation.