overload in Python
Several signatures for one function, so the checker knows what comes back.
from typing import overload
@overload
def parse(text: str) -> int:
...
@overload
def parse(text: str, default: str) -> int | str:
...
def parse(text, default=None):
try:
return int(text)
except ValueError:
if default is None:
raise
return default
print(parse("42"), parse("x", "fallback"))
print(parse.__name__)
How it works
- Each
@overloadstub declares one calling shape. - The real implementation follows, untyped by overload.
- At run time only the implementation exists.
Keywords and builtins used here
defexceptifintparseprintraisereturnstrtry
The run, in numbers
- Lines
- 24
- Characters to type
- 319
- Tokens
- 94
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 51 seconds.
Step 4 of 4 in Typing in depth, step 44 of 53 in Pythonic Python.