I often use type hints to help document code & occasionally when the type signatures are too complex & repeatedly used I alias them like this:
MyType = Dict[Tuple[int,...], float] # ex: cluster & score.
Is there a way in python to parametrize type parts? A common use case is when I want to describe functions returning generators. For instance the Generator[int, None, None]
notation works but the unused None
details could be hidden in a new type.
Does there exists something like partial
functions on types where we can “lock in” some of the sub type parameters? Or perhaps this is doable via Generics
? Conceptually I’m thinking of something like this:
MyGenType[int] = functools.partial(Generator, None, None) # pseudo code!
This did it:
from typing import Generator, TypeVar
T = TypeVar("T")
MyGenType = Generator[T, None, None]
def fn(n: int) -> MyGenType[str]:
return (str(_) for _ in range(n))
list(fn(3)) # ['0', '1', '2']