Skip to content

mypy fails to narrow Union[float,int] to float after isinstance(x, float) #6060

@DarwinAwardWinner

Description

@DarwinAwardWinner

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.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions