Types
Overloads
The overload stubs give static tools precise call shapes: integer in, integer out; string in, string out.
Source
from typing import overload
@overload
def double(value: int) -> int: ...
@overload
def double(value: str) -> str: ...
print("static signatures only")Output
static signatures onlyThere is still one runtime implementation. It must accept every shape promised by the overloads.
Source
def double(value: int | str) -> int | str:
return value * 2
print(double(4))
print(double("ha"))Output
8
hahaOnly the implementation's annotations are visible on the runtime function. The overload declarations were for the type checker.
Source
print(double.__annotations__)Output
{'value': int | str, 'return': int | str}Notes
- Put
@overloaddeclarations immediately before the implementation. - Overloads improve static precision; they do not create runtime dispatch.
- If all callers can work with one broad return type, a simple union annotation is usually enough.
See also
- related: Type Hints
- related: Union and Optional Types
- related: Generics and TypeVar
Run the complete example
Expected output
8
haha
{'value': int | str, 'return': int | str}
Execution time appears here after you run the example.