31
loading...
This website collects cookies to deliver better user experience
TypeVar
s, for fun and profit.arg
?def identity(arg):
return arg
def identity(arg: Any) -> Any:
return arg
Any
, the type checker will not understand how this function works: as far as it's concerned, the function can return anything at all. The return type doesn't depend on the type of arg
.def identity_int(arg: int) -> int:
return arg
def identity_int(arg: str) -> str:
return arg
def identity_list_str(arg: list[str]) -> list[str]:
return arg
...
This doesn't scale well. Are you going to replicate the same function 10 times? Will you remember to keep them in sync?
What if this is a library function? You won't be able to predict all the ways people will use this function.
identity
function:from typing import TypeVar
T = TypeVar("T")
def identity(arg: T) -> T:
return arg
def triple(string: Union[str, bytes]) -> Union[str, bytes]:
return string * 3
str
, you get str
. If you pass in bytes
, you get bytes
" -- sounds like a job for a type variable.str
or bytes
(and their subclasses, of course).AnyString = TypeVar("AnyString", str, bytes)
def triple(string: AnyString) -> AnyString:
return string * 3
unicode_scream = triple("A") + "!"
bytes_scream = triple(b"A") + b"!"
list
or Iterable
.def remove_falsey_from_list(items: list[T]) -> list[T]:
return [item for item in items if item]
def remove_falsey(items: Iterable[T]) -> Iterator[T]:
for item in items:
if item:
yield item
mypy
documentation on generic functions: https://mypy.readthedocs.io/en/stable/generics.html#generic-functions