Skip to content

mypy fails to narrow a type when isinstance() is wrapped inside a function #8322

Closed
@kprzybyla

Description

@kprzybyla

I stumbled upon this couple of times so I guess it's fairly reasonable to report this. Currently mypy understand isinstance() and will properly resolve types when isinstance() is used inside if statement:

from typing import Union

Complex = Union[int, str]

x: Complex

if isinstance(x, int):
    reveal_type(x)
example.py:8: note: Revealed type is 'builtins.int'

However, if you move isinstance() call to function that basically wraps it, mypy fails to narrow a type of variable.

from typing import Union

Complex = Union[int, str]

x: Complex

def is_integer(value: Complex) -> bool:
    return isinstance(value, int)

if is_integer(x):
    reveal_type(x)
example.py:11: note: Revealed type is 'Union[builtins.int, builtins.str]'

This is somewhat annoying if you have a complex isinstance() call that you don't want to copy in your code over and over again but simply hide it under a descriptive function name.

This might be somehow related to #4573.

Versions

mypy 0.761
Python 3.7.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions