-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder
Description
Mypy fails to typecheck the following valid code:
from typing import Union
def maybe_convert_to_int(x: Union[float,int]) -> Union[float,int]:
'''Convert x from float to int if it can be done losslessly.'''
if isinstance(x, float):
# x must be a float here, so this is a legal operation, but
# mypy still thinks its type is Union[float,int]
assert isinstance(x, float)
if x.is_integer():
x = int(x)
return x
When I run mypy on it, I get:
$ mypy ~/temp/test_mypy.py
temp/test_mypy.py:8: error: Item "int" of "Union[float, int]" has no attribute "is_integer"
$ python --version
Python 3.7.1
$ mypy --version
mypy 0.650
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 operation float.is_integer
. If I replace the assertion with x = float(x)
, that satisfies the type checker.
GregHilston and TylerYep
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder