-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
generic fails to narrow, something to do with using NoReturn
on contravariant generic
#11508
Comments
NoReturn
NoReturn
from typing import Generic, NoReturn, TypeVar
T_cont = TypeVar("T_cont", contravariant=True)
class Foo(Generic[T_cont]):
...
foo = Foo[object]()
a1: list[Foo[bool]] = [foo]
a2: list[Foo[NoReturn]] = [foo] # error: Incompatible types in assignment (expression has type "List[Foo[int]]", variable has type "List[Foo[NoReturn]]") [assignment]
# main.py:12: note: "List" is invariant 🤔 |
You pointed out that "the error goes away if you change this to [foo]". That looks like a bug. It should be an error in this case too. Keep in mind that no type is assignable to Also, PEP 484 specifically says:
So mypy should generate an error for the type annotation |
NoReturn
NoReturn
on contravariant generic
So mypy should remove a lot of functionality it has implemented around |
I'm not sure what you mean by "remove a lot of functionality it has implemented around |
mypy lets you use it like a from typing import NoReturn
foo: NoReturn
bar: int = foo (relevant discussion from a previous issue i raised: #11291 (comment)) |
Yes, you're right that def assert_never(x: NoReturn) -> NoReturn:
assert False, "Unhandled type: {}".format(type(x).__name__)
def handle_my_union(x: int | str) -> None:
if isinstance(x, int):
pass
elif isinstance(x, str):
pass
else:
assert_never(x) You can find more details about this use case if you search the issue tracker for I guess this is a use case that PEP 484 didn't anticipate and technically doesn't allow (since This works because of the property I mentioned above. The only type that can be assigned to |
https://mypy-play.net/?mypy=latest&python=3.10&gist=175deca029e02ea95af74f7c4a02856c
The text was updated successfully, but these errors were encountered: