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

@overload with multiple Generic[Any] #2157

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

Am I missing something, or is it impossible to annotate op in a way that satisfies the assert_type test-suite in the example below?

from typing import Any, overload, assert_type
class A[T]: # covariant
 def get(self) -> T: ...
@overload
def op(l: A[None], r: A[None]) -> A[None]: ...
@overload
def op(l: A[None], r: A[Any]) -> A[None]: ...
@overload
def op(l: A[Any], r: A[None]) -> A[None]: ...
@overload
def op(l: A[Any], r: A[Any]) -> A[Any]: ...
def op(l, r):
 # dummy implementation:
 if l.get() is None or r.get() is None:
 return A[None]()
 return A[Any]()
def test(x: A[None], y: A[Any]) -> None:
 assert_type(op(x, x), A[None])
 assert_type(op(x, y), A[None]) # ❌️: (mypy, zuban)
 assert_type(op(y, x), A[None]) # ❌️: (mypy, zuban)
 assert_type(op(y, y), A[Any]) # ❌️: (pyright, ty, pyrefly)

The schema is relevant for type hinting numeric types that interact with math.nan / nullable values.

You must be logged in to vote

Replies: 1 comment

Comment options

The alternative of not preserving None in the mixed case makes mypy and zuban happy, but gives even worse results on the other type checkers:

from typing import Any, overload, assert_type
class A[T]: # covariant
 def get(self) -> T: ...
@overload
def op(l: A[None], r: A[None]) -> A[None]: ...
@overload
def op(l: A[None], r: A[Any]) -> A[Any]: ...
@overload
def op(l: A[Any], r: A[None]) -> A[Any]: ...
@overload
def op(l: A[Any], r: A[Any]) -> A[Any]: ...
def op(l, r):
 # dummy implementation:
 if l.get() is None or r.get() is None:
 return A[None]()
 return A[Any]()
def test(x: A[None], y: A[Any]) -> None:
 assert_type(op(x, x), A[None])
 assert_type(op(x, y), A[Any]) # ❌️: (pyright, pyrefly, ty)
 assert_type(op(y, x), A[Any]) # ❌️: (pyright, pyrefly, ty)
 assert_type(op(y, y), A[Any]) # ❌️: (pyright, pyrefly, ty)
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
1 participant

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