Sub topic 17
Describing varying signatures with overloads
This chapter assumes you can write annotated functions, use X | None unions, and run mypy or pyright. It also assumes you have seen TypeVar.
The problem: one function, several return types
Some functions return different types depending on their arguments. A union return type is accurate but unhelpful, because every caller must narrow it.
def parse(value: str | bytes) -> str | bytes:
if isinstance(value, bytes):
return value.decode()
return value.encode()Here a str argument always gives bytes, and a bytes argument always gives str. The signature -> str | bytes hides that link. A caller who passes "abc" gets str | bytes and must check the result before calling bytes methods on it.
Writing overloads
The @overload decorator from typing lets you declare several signatures for one function. Each declaration has a body of .... A final implementation without the decorator does the real work.
from typing import overload
@overload
def parse(value: str) -> bytes: ...
@overload
def parse(value: bytes) -> str: ...
def parse(value: str | bytes) -> str | bytes:
if isinstance(value, bytes):
return value.decode()
return value.encode()
encoded = parse("abc")
decoded = parse(b"abc")
reveal_type(encoded) # checker output: bytes
reveal_type(decoded) # checker output: strreveal_type is understood by mypy and pyright, and Python 3.11 and later also provides it in typing. Running this file with the interpreter fails with a NameError on versions before 3.11, so delete those two lines or run only the checker.
How a checker uses them
The checker tries each overload from top to bottom and picks the first one whose parameters match the call. The implementation signature is not visible to callers. In the example, parse(3) is an error even though the implementation never mentions int.
The checker also verifies that the implementation accepts every overload. If the implementation were narrower, such as value: str, the checker would report an inconsistency.
A common case: optional results
Overloads work well with Literal to change a return type based on a flag.
from typing import Literal, overload
@overload
def read_setting(name: str, required: Literal[True]) -> str: ...
@overload
def read_setting(name: str, required: Literal[False]) -> str | None: ...
def read_setting(name: str, required: bool) -> str | None:
settings = {"mode": "fast"}
if required and name not in settings:
raise KeyError(name)
return settings.get(name)
print(read_setting("mode", True).upper())With required=True, the checker knows the result is str, so .upper() needs no None check.
Common errors
- Putting a more general overload first. It matches every call, so later overloads never apply. Order from most specific to most general.
- Forgetting the implementation. Overloads without one fail at runtime when the function is called.
- Writing overloads that differ only in return type. The checker reports overlapping signatures with incompatible returns.
- Using overloads when a
TypeVarwould do. If the output type simply equals the input type, a generic function is simpler.
Exercise
Why does parse(3) fail type checking even though the implementation signature is value: str | bytes?
Show answer
Callers see only the @overload signatures. Neither accepts int, and the implementation signature is hidden from callers, so the checker reports an error.
Exercise
You write @overload def f(x: object) -> int: ... before @overload def f(x: str) -> str: .... What goes wrong?
Show answer
Every argument matches object, so the checker always picks the first overload. The str overload is never used. Put the more specific str overload first.