Skip to content

Annotate a Python function so that it narrows down the return type of an union involving a typevar #1639

Answered by erictraut
AlexandreDecan asked this question in Q&A
Discussion options

You must be logged in to vote

For polymorphic functions like this, typing.overload is usually the best approach.

Code sample in pyright playground

from typing import TypeVar, overload

T = TypeVar("T", bound=int)

@overload
def g(x: T, y: T) -> tuple[T, T]: ...
@overload
def g(x: T, y: str) -> tuple[T, str]: ...
@overload
def g(x: str, y: T) -> tuple[str, T]: ...
@overload
def g(x: str, y: str) -> tuple[str, str]: ...

def g(x: T | str, y: T | str) -> tuple[T | str, T | str]:
    return x, y

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by AlexandreDecan
Comment options

You must be logged in to vote
1 reply
@AlexandreDecan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants