Skip to content

isinstance(foo, SomeType | None) fails to narrow variable, while isinstance(foo, SomeType | type(None)) succeeds #17530

@neob91-close

Description

@neob91-close

Bug Report

It appears that isinstance(a, str | None) fails to narrow the variable a to str | None. Its type remains to be str | int | None.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=883cae3c57a4ddca5c4406a0f7cd89d3

def all_good() -> int:
    a: str | int | None

    if isinstance(a, str | type(None)):
        return 0

    return a  # ok


def false_positive() -> int:
    a: str | int | None

    if isinstance(a, str | None):
        return 0

    return a  # error

Expected Behavior

I would expect that isinstance(a, str | None) would narrow the variable a to str | None.

Actual Behavior

The type of a is not narrowed to str | None and remains of type str | int | None.

main.py:16: error: Incompatible return value type (got "str | int | None", expected "int")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.10.1
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions