I wonder what’s the right way to type annotate a python function as below?
JavaScript
x
5
1
def f(value):
2
if isinstance(value, str):
3
return None
4
return value
5
This is a toy example that is analogous to a python I encountered that needs type annotated. Using Union
like
JavaScript
1
5
1
def f(value: Union[float, int, str]) -> Union[float, int, None]:
2
if isinstance(value, str):
3
return None
4
return value
5
doesn’t feel right because it doesn’t enforce the rules
- an
int
input must result in anint
output. - a
float
input must result in afloat
output. - a
str
input must result inNone
.
Let’s assume the input can only be one of int/float/str
.
Advertisement
Answer
You can use typing.overload
to narrow the types of return values based on the types of the arguments:
JavaScript
1
16
16
1
from typing import overload
2
3
@overload
4
def f(value: str) -> None:
5
6
@overload
7
def f(value: int) -> int:
8
9
@overload
10
def f(value: float) -> float:
11
12
def f(value: int|float|str) -> int|float|None:
13
if isinstance(value, str):
14
return None
15
return value
16
Note that the actual implementation uses a union of all the possible argument and return types.
If a call to the function conforms to one of the overload stubs, the appropriate return type is inferred:
JavaScript
1
3
1
reveal_type(f("foo")) # revealed type is "None"
2
reveal_type(f(123)) # revealed type is "builtins.int"
3