Closed
Description
- Mypy's current behaviour:
x: int | None
if x == None:
x # "Union[builtins.int, None]"
else:
x # "Union[builtins.int, None]"
- Pyright's current behaviour:
x: int | None
if x == None:
x # x is None
else:
x # x is int
- I think the ideal solution would be:
x: int | None
if x == None:
x # "Union[builtins.int, None]"
else:
x # "builtins.int"
This Mypy code comment seems to favour solution 2.
I am asking because if Mypy would follow solution 2 or 3, in
-based narrowing of optional types could be implemented more consistently.
Activity
hauntsaninja commentedon Nov 14, 2024
I think both 2 and 3 are fine. If we go with 3, we should look at presence of
__eq__
(int
has__eq__
defined, not sure why, dates back to 2015)tyralla commentedon Nov 14, 2024
Did you mean we should check for
__eq__
when going for solution 2?If so, this could be an additional safety net for most cases. Then, the modified solution 2 would only result in wrong narrowing for subtypes that override
__eq__
strangely:I think, for complete safety, we would have to combine looking for
__eq__
with checking forfinal
:Support `==`-based narrowing of Optional
==
-based narrowing of Optional #18163Support `==`-based narrowing of Optional (python#18163)