Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Distribute return type over union #2047

Unanswered
randolf-scholz asked this question in Q&A
Discussion options

Inspired by microsoft/pyright#10673, I looked at this simple example: Code sample in pyright playground

from collections.abc import Sequence
def listify[T](x: Sequence[T]) -> list[T]:
 return list(x)
def func(x: Sequence[str] | Sequence[int]):
 y = listify(x)
 reveal_type(y) # list[str | int]
 print(y)

It feels like the revealed type is not actually what we want here. The desirable inference is imo list[str] | list[int].

Is there simple way to annotate listify to make the return type distribute over unions, or is this a general type-checker limitation?

What seems to happen here is that we assign Sequence[str] | Sequence[int] <: Sequence[str | int] = Sequence[T], so we pick T = int | str. However, in principle wouldn't it be more precise if the type checker, when seeing a UnionType as an argument, passes every member separately and yields the UnionType of the individual return types?

I guess with multiple arguments this runs into combinatoric explosion...

You must be logged in to vote

Replies: 0 comments

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

AltStyle によって変換されたページ (->オリジナル) /