Skip to content

Specifying type for Generic Function #943

Discussion options

You must be logged in to vote

There is already a way to help out type checkers in ambiguous cases, use PEP 526 variable annotations for the result:

def to_list(value: Iterable[T] | T) -> list[T]:
    ...

def func1(x: list[int] | int):
    y: list[int] = to_list(x)
    reveal_type(y)

Most type checkers are capable of using this extra information during type inference, e.g. mypy calls this type context and pyright calls it bidirectional interface.

In the specific case of the to_list example, especially if you look at the proposed implementation in the linked issue, you're actually better served with overloads:

@overload
def to_list(value: Iterable[T]) -> list[T]: ...
@overload
def to_list(value: T) -> list[T]: ...

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by hmc-cs-mdrissi
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #938 on November 14, 2021 22:47.