patternpythonnoneModerate
Python overload Decorator for Multiple Call Signatures
Viewed 0 times
Python 3.5+
overloadmultiple signaturesfunction overloadingLiteral typereturn type
Problem
A function accepts multiple argument types and returns different types based on input. A single signature with Union types loses the connection between input and output types.
Solution
Use @overload to define multiple typed signatures for the same function.
from typing import overload, Literal
@overload
def parse_value(value: str, as_type: Literal['int']) -> int: ...
@overload
def parse_value(value: str, as_type: Literal['float']) -> float: ...
@overload
def parse_value(value: str, as_type: Literal['str']) -> str: ...
def parse_value(value: str, as_type: str) -> int | float | str:
if as_type == 'int':
return int(value)
elif as_type == 'float':
return float(value)
return value
# Type checker now knows the return type based on as_type
result1 = parse_value('42', 'int') # int
result2 = parse_value('3.14', 'float') # float
result3 = parse_value('hello', 'str') # str
# Without overload, result would be int | float | str
# and you'd need to type-narrow manuallyWhy
Overloads let the type checker pick the correct return type based on which signature matches the call. Only the implementation signature (without @overload) is used at runtime.
Gotchas
- The implementation signature (after all @overload stubs) must NOT have @overload and is never visible to callers.
- Overload stubs must have '...' as the body — they are never executed.
- Overloads are checked in order — more specific overloads must come before general ones.
Revisions (0)
No revisions yet.