Reputation: 12283
I have a function:
T = typing.TypeVar('T', str, list[str])
def f(arg: T) -> T:
...
AFAICS this means the following are valid:
f(str)
→ str
f(list[str])
→ list[str]
or in other words when a string is given, a string is returned; when a list of strings is given, a list of strings is returned.
Now I would like to express the type of a function that when a single string is given returns a bool
, and if a list of strings is given returns a list[bool]
.
How would I go about that?
Upvotes: 3
Views: 91
Reputation: 12283
Thanks to the hint in comments by @koyeung
@typing.overload
def f(arg: str) -> bool:
...
@typing.overload
def f(arg: list[str]) -> list[bool]:
...
def f(arg):
if isinstance(arg, list):
return ... # implementation for list
... # implementation for str
Upvotes: 2