scravy
scravy

Reputation: 12283

python typing: result depending on arguments

I have a function:

T = typing.TypeVar('T', str, list[str])
def f(arg: T) -> T:
    ...

AFAICS this means the following are valid:

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

Answers (1)

scravy
scravy

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

Related Questions