Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
neob91-close opened this issue Jul 15, 2024 · 1 comment
Labels
bug mypy got something wrong

Comments

@neob91-close
Copy link
Contributor

neob91-close commented Jul 15, 2024

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
@neob91-close neob91-close added the bug mypy got something wrong label Jul 15, 2024
@ngnpope
Copy link

ngnpope commented Jul 17, 2024

Duplicate of #17413. This has been fixed on the master branch by #17415.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants