-
-
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
mypy fails to narrow Union[float,int] to float after isinstance(x, float) #6060
Comments
This is because some special-casing in mypy called "type promotions". The point is that We try to ignore the type promotions while working with def maybe_convert_to_int(x: float) -> float:
if isinstance(x, int):
return x
if x.is_integer():
x = int(x)
return x |
@Michael0x2a was among the last who worked with this code, so probably he has the most context. |
I discovered a workaround that eliminated this code entirely for my specific use case. The reason for this code was to ensure that a float like However, I guess this is still a bug in the general case. |
As described here: python/mypy#6060 As a special case, int is considered a subtype of float, so the type union is redundant.
This pull request resolves python#6060 by modifying `conditional_type_map` function in `checker.py` to ignore promotions.
This pull request resolves #6060 by modifying `conditional_type_map` function in `checker.py` to ignore promotions.
I believe I'm still experiencing this issue:
Still getting a mypy error of
|
I can also reproduce this, or a similar issue having to do with statement reachability, both on mypy 0.740 and master (mypy 0.750+dev.e97377c454a1d5c019e9c56871d5f229db6b47b2) from typing import Union
def get_number_type(v: Union[float, int]) -> str:
if isinstance(v, float):
return "float"
if isinstance(v, int):
return "int" # Error: Statement is unreachable Changing the order of the isinstance checks makes the error go away. |
Mypy fails to typecheck the following valid code:
When I run mypy on it, I get:
I would expect this program to pass the type checker, since I am using
isinstance
to narrow the type to float before performing the float-specific operationfloat.is_integer
. If I replace the assertion withx = float(x)
, that satisfies the type checker.The text was updated successfully, but these errors were encountered: