Beispiel 1. Verwendung von TypeVar:
Code: Select all
from typing import TypeVar
StrOrInt = TypeVar("StrOrInt", str, int)
def return_same_type_typevar(x: StrOrInt) -> StrOrInt:
if isinstance(x, str):
# process str
return x
else:
# process int
return x
Code: Select all
from typing import overload
@overload
def return_same_type_overload(x: str) -> str:
...
@overload
def return_same_type_overload(x: int) -> int:
...
def return_same_type_overload(x):
if isinstance(x, str):
# process str
return x
else:
# process int
return x
Natürlich ist dies ein triviales Beispiel. Der Code, den ich mir ansehe, würde wahrscheinlich eher eine Pandas-Serie oder einen DataFrame als Eingabe verwenden und nicht str und int.
Mobile version