pyright icon indicating copy to clipboard operation
pyright copied to clipboard

numeric tower and type narrowing by 'isinstance'

Open pinterior opened this issue 4 years ago • 2 comments

Describe the bug

for argument (or even variable) x: float, isinstance(x, float) should not be assumed always True, because int is still not a subtype of float.

PEP-484:

when an argument is annotated as having type float, an argument of type int is acceptable

To Reproduce

from typing_extensions import reveal_type

# pyright: strict

def f(x: float):
    if isinstance(x, float):
        raise Exception()
    return "foo"

reveal_type(f)
reveal_type(f(1))
error: Unnecessary isinstance call; "float" is always an instance of "float" (reportUnnecessaryIsInstance)
information: Type of "f" is "(x: float) -> NoReturn"
information: Type of "f(1)" is "NoReturn"```
Runtime type is 'function'
Runtime type is 'str'

Expected behavior

type (float) -> str is infered for f

VS Code extension or command-line

command-line tool 1.1.280

Additional Context

matching against Union[str, float] with two cases (str and float) should be warned for non-exhaustive match? 🤔

pinterior avatar Nov 16 '22 15:11 pinterior

This is an unfortunate inconsistency between the static type system and the runtime. In the static type system, int is a subtype of float, but in the runtime isinstance(x, float) returns False if x is an int. There is no good resolution to this inconsistency. If we were to sometimes treat int as a subclass of float and other times not, it will create many new problems. We therefore consistently treat int as though it is a proper subclass of float as indicated in PEP 484.

The reportUnnecessaryIsInstance error is an unfortunate side effect of this decision. You will need to find a way to work around this issue in your code. A # type: igore or # pyright: ignore[reportUnnecessaryIsInstance] would work to suppress this error if you don't want to change your code.

erictraut avatar Nov 16 '22 16:11 erictraut

sure, thanks.

pinterior avatar Nov 16 '22 18:11 pinterior