Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Overload Type Hints: Multiple Signatures

Use Python's typing.overload to declare multiple type signatures for one function and improve static type checking accuracy.

~4 min readPython
#typing#type hints#overload#mypy
A diagram showing one Python function with multiple type signature arrows converging into a single implementation block.

When a Python function accepts different argument types, or returns different result types depending on the input, a single type hint can be imprecise. Python's typing.overload mechanism lets you declare multiple type signatures for one function. Static type checkers such as mypy and Pyright can then infer the correct return type at each call site based on the argument types.

What typing.overload Declares

The @overload decorator marks a function stub as a type-signature declaration. You write several decorated stubs, each with a distinct signature, followed by one undecorated implementation. The stubs are not executed; they exist for static analysis.

python
import json from typing import overload @overload def parse_config(text: str) -> dict: ... @overload def parse_config(raw: bytes) -> dict: ... def parse_config(source: str | bytes) -> dict: if isinstance(source, bytes): source = source.decode('utf-8') return json.loads(source)

The decorated stubs do not run when the function is called. The final undecorated definition is the real implementation.

How Type Checkers Pick an Overload

Type checkers evaluate overloads in declaration order and select the first signature that matches the call. Ordering is therefore part of the API contract.

Consider this reversed ordering:

python
@overload def convert(value: object) -> str: ... @overload def convert(value: int) -> int: ... def convert(value: object) -> object: return value if isinstance(value, int) else str(value)

A call like convert(42) matches the first overload because int is a subtype of object, so the checker infers the return type as str instead of int. The narrower overload never gets a chance. Put more specific signatures first:

python
@overload def convert(value: int) -> int: ... @overload def convert(value: object) -> str: ... def convert(value: object) -> object: return value if isinstance(value, int) else str(value)

Now convert(42) is inferred as int, and any non-int argument is inferred as str.

Rules the Implementation Must Follow

Several constraints apply when you use typing.overload:

  • All overload declarations must appear before the implementation.
  • The implementation must be the last definition of the name.
  • The implementation's signature must be broad enough to accept every argument combination covered by the overloads, typically using union types or Any.
  • The decorated stubs conventionally contain only ..., because their bodies are not executed.

If no undecorated implementation follows, the module-level name remains an overloaded stub. On Python 3.11 or later, calling it raises NotImplementedError, which is a common failure mode during refactoring. On earlier Python versions, @overload returns the stub unchanged, so a missing implementation may not be detected at runtime.

The | union syntax in these annotations requires Python 3.10 or later. On older versions, use typing.Union[str, bytes]. The @overload decorator is part of the standard typing module, so no third-party package is needed.

A Practical Example: Parsing Different Input Formats

A realistic use case is a parser that accepts JSON Lines data as a string, raw bytes, or an already open text stream:

python
from typing import overload, TextIO import io, json @overload def load_events(text: str) -> list[dict]: ... @overload def load_events(raw: bytes) -> list[dict]: ... @overload def load_events(stream: TextIO) -> list[dict]: ... def load_events(source: str | bytes | TextIO) -> list[dict]: if isinstance(source, bytes): source = source.decode('utf-8') if isinstance(source, str): source = io.StringIO(source) return [json.loads(line) for line in source]

Each overload states one accepted input form. The checker knows the return type is list[dict] for each branch. Because the return type is the same for every overload, a single union-typed signature would also be sufficient here. Overloads matter more when the return type varies by input or when you need to restrict combinations of arguments, as the following examples show.

Combining Overloads with TypeVars

Overloads become more powerful when combined with TypeVar to express relationships between generic types:

python
from typing import TypeVar, overload T = TypeVar('T') @overload def first(items: list[T]) -> T: ... @overload def first(items: tuple[T, ...]) -> T: ... def first(items: list[T] | tuple[T, ...]) -> T: return items[0]

Here each overload captures the element type from the container type. A call like first([1, 2, 3]) is inferred as int, and first(('a', 'b')) is inferred as str. A single signature with Sequence[T] would also work, but overloads let you restrict the accepted container types explicitly.

Runtime Cost and Introspection Behavior

typing.overload does not add a per-call wrapper around the implementation. The implementation replaces the overload stubs in the module namespace, so the ordinary function body is what runs at runtime. The decorator may record overload metadata at definition time; for example, Python 3.11+ records overloads so typing.get_overloads can retrieve them. That metadata does not add dispatch overhead to function calls.

One runtime caveat: tools that inspect function signatures, such as inspect.signature, see the implementation's signature, not the overloads. If your code uses inspect to generate documentation or validate arguments, the overloads will not be visible through that API. Python 3.11 added typing.get_overloads for explicit runtime access to the declared overloads. Static type checkers remain the primary consumers.

When Overloads Add More Noise Than Value

Overloads are not the right tool for every function with multiple input types. If the return type does not depend on the argument types, a union type in a single signature is simpler:

python
def normalize(value: str | bytes) -> str: return value.decode() if isinstance(value, bytes) else value

Adding overloads here would duplicate the signature for no benefit. Similarly, if the relationship between input and output can be expressed with a TypeVar, prefer the TypeVar:

python
from typing import TypeVar T = TypeVar('T') def identity(value: T) -> T: return value

Overloads earn their place when the return type genuinely varies by argument type, or when you need to restrict argument combinations that a single signature cannot express. Overusing them makes the module harder to maintain because every signature change must be applied in multiple places. When the set of accepted input types grows, review whether the overloads still reflect the implementation's actual behavior; a mismatch between the declared signatures and the runtime logic is a common source of subtle type-checker bugs.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.