Sub topic 17
Describing varying signatures with overloads
This chapter assumes you can annotate functions with Callable, unions, Literal, and TypeVar, and that you can run mypy or pyright on a file. You will learn how @overload describes a function whose return type depends on its arguments, and when a simpler tool is the better choice.
The problem overloads solve
A union return type is accurate but inconvenient. Suppose a function returns int for int input and str for str input:
def double(value: int | str) -> int | str:
return value * 2
result = double(4)
# A checker sees int | str, so result + 1 is reported as an error.The annotation does not say that the output type follows the input type. The caller has to narrow the result with isinstance even though the answer is obvious from the call. An overload fixes this by listing each valid call shape separately.
Writing an overloaded function
An overloaded function has two or more signature declarations, each decorated with @overload and each with the body .... A single implementation follows them and has no decorator.
from typing import overload
@overload
def double(value: int) -> int: ...
@overload
def double(value: str) -> str: ...
def double(value: int | str) -> int | str:
return value * 2
print(double(4)) # 8, and a checker infers int
print(double("ab")) # abab, and a checker infers strThe rules a checker applies:
- There must be at least two
@overloadsignatures. - The implementation comes last and is not decorated.
- Callers see only the overload signatures. The implementation's signature is hidden from them, so
double(1.5)is an error even though the implementation's union would not catch it by itself. - The implementation must be broad enough to accept every overload. The checker reports an error if an overload cannot be handled by it.
In a stub file (.pyi) you write only the overload signatures and no implementation.
What happens at runtime
@overload does not dispatch calls. When Python runs the file, each definition rebinds the name double, so the last one, the implementation, is the only function that exists. The implementation must therefore do the real branching itself. Only the checker uses the overload signatures.
If you leave out the implementation, the name is bound to a placeholder. In Python 3.11 and later, calling it raises NotImplementedError. Python 3.11 also added typing.get_overloads() for inspecting registered overloads. This is rarely needed.
Return types that depend on a flag
The most common real use is a boolean or string argument that changes the return type. Pair Literal with overloads so each value maps to one type.
from pathlib import Path
from typing import Literal, overload
@overload
def read(path: str, *, as_bytes: Literal[True]) -> bytes: ...
@overload
def read(path: str, *, as_bytes: Literal[False] = False) -> str: ...
def read(path: str, *, as_bytes: bool = False) -> str | bytes:
if as_bytes:
return Path(path).read_bytes()
return Path(path).read_text()
Path("demo.txt").write_text("hello")
text = read("demo.txt") # str
data = read("demo.txt", as_bytes=True) # bytes
print(text, data)The second overload carries the default, so read("demo.txt") matches it. A call that passes a plain bool variable, such as read(p, as_bytes=flag), matches neither overload. Many checkers accept it only if you add a third overload with as_bytes: bool and return str | bytes. Adding that fallback is usually worthwhile.
Different argument counts
Overloads can also describe optional arguments that change the result. The standard example is a lookup with an optional default:
import os
from typing import overload
@overload
def get_env(name: str) -> str | None: ...
@overload
def get_env(name: str, default: str) -> str: ...
def get_env(name: str, default: str | None = None) -> str | None:
return os.environ.get(name, default)
home = get_env("HOME", "/tmp")
print(home.upper()) # fine: a checker knows home is strWithout the second overload, every caller would have to check for None even after supplying a default.
How a checker picks an overload
The checker tries the overloads in the order written and uses the first one whose parameters accept the call. This ordering has a consequence: put narrower types before broader ones.
from typing import overload
@overload
def describe(flag: bool) -> str: ...
@overload
def describe(flag: int) -> int: ...
def describe(flag: int) -> str | int:
if isinstance(flag, bool):
return "yes" if flag else "no"
return flag * 10
print(describe(True)) # yes
print(describe(3)) # 30bool is a subclass of int. If the int overload came first, describe(True) would match it and the checker would infer int, while the runtime returns a string. The implementation tests bool before anything else for the same reason.
Common errors
| Checker message (wording varies) | Cause | Fix |
|---|---|---|
| Single overload definition, multiple required | Only one `@overload` was written | Add a second overload or remove the decorator |
| Overloaded function implementation does not accept all possible arguments | The implementation's parameters are narrower than an overload's | Widen the implementation, usually with a union |
| Overloaded function signatures 1 and 2 overlap with incompatible return types | A broad overload comes before a narrow one that returns something different | Reorder, or reconsider whether overloads fit |
| No overload variant matches argument types | The call does not fit any signature | Fix the call, or add the missing overload |
| Missing implementation | Overloads in a `.py` file with no final definition | Add the implementation (stubs are exempt) |
Overlap errors deserve care. If two signatures overlap and return incompatible types, the checker cannot tell which one is correct for some inputs. Silencing the error with # type: ignore hides a real inconsistency.
Overloads in classes
Overloads work on methods in the same way. Put @overload under @staticmethod or @classmethod if you use them, and keep self unannotated.
from typing import overload
class Grid:
def __init__(self, cells: list[int]) -> None:
self.cells = cells
@overload
def __getitem__(self, index: int) -> int: ...
@overload
def __getitem__(self, index: slice) -> list[int]: ...
def __getitem__(self, index: int | slice) -> int | list[int]:
return self.cells[index]
grid = Grid([5, 6, 7])
print(grid[0]) # 5, an int
print(grid[0:2]) # [5, 6], a list[int]This is the pattern used for sequence-like classes, where an integer index returns an element and a slice returns a collection.
Alternatives to try first
Overloads add duplicated signatures that must be kept in sync with the implementation. Consider these first.
| Situation | Better tool |
|---|---|
| Output has the same type as input, for any type | `TypeVar`, as in `def first(items: Sequence[T]) -> T` |
| Two arguments must be both `str` or both `bytes` | A constrained `TypeVar` such as `AnyStr` |
| The return type does not depend on the arguments | A plain union return, or two separate functions |
| A flag selects behavior in a way a caller reads as a different action | Two functions with distinct names |
A short example of the constrained form:
from typing import AnyStr
def join_parts(a: AnyStr, b: AnyStr) -> AnyStr:
return a + b
print(join_parts("ab", "cd"))
print(join_parts(b"ab", b"cd"))Mixing str and bytes is rejected by the checker, which is what you want, and you wrote one signature instead of two.
Use overloads when the relationship between argument types and result type cannot be expressed by a TypeVar: a Literal flag, a presence or absence of an argument, or specific unrelated type pairs.
Exercises
Exercise
A function load(path: str, parsed: bool = False) returns a dict[str, int] when parsed is True and the raw str text otherwise. Write the overload signatures (bodies as ...) so a checker infers the correct type for load("a.json") and load("a.json", parsed=True).
Show answer
Use Literal flags, with the default on the str overload:
@overload
def load(path: str, parsed: Literal[True]) -> dict[str, int]: ...
@overload
def load(path: str, parsed: Literal[False] = False) -> str: ...
The implementation then takes parsed: bool = False and returns dict[str, int] | str. Without Literal, both overloads would accept any bool and the first would always win.
Exercise
Your overloaded describe function has int as the first overload and bool as the second. What does a checker infer for describe(True), and why is that a problem?
Show answer
It infers the int overload's return type, because bool is a subclass of int and the first matching overload wins. The bool overload is never reached, so the inferred type disagrees with the value the implementation returns at runtime. Put bool first. (The checker may also report that the signatures overlap.)