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

Defining Multiple Signatures with Overload for Static Analysis

Provide multiple function signatures for different input types using typing.overload while maintaining a single runtime implementation.

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

  1. The Overloads: The lines decorated with @overload are 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.
  2. 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 @overload signatures 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.