Skip to content

type narrowing with isinstance does not work consistently with Any #20363

Description

@jgogstad

Bug Report

Type narrowing with isinstance doesn't happen if it's used in a conditional statement with and or or

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.13&flags=strict&gist=fb4efdf001e261dd16d2605c7488537e

from typing import Any


def foo() -> str:
    a: dict[str, Any] = {"foo": "bar"}
    foo = a.get("foo")
    if foo and isinstance(foo, str):
        return foo

    return ""

it works if we remove the and:

from typing import Any


def foo() -> str:
    a: dict[str, Any] = {"foo": "bar"}
    foo = a.get("foo")
    if isinstance(foo, str):
        return foo

    return ""

Expected Behavior

isinstance should narrow the type regardless of whether it's used in a conjunction or not

Your Environment

  • Mypy version used: 1.18.2
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.13.9

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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