Thanks to visit codestin.com
Credit goes to github.com

Skip to content

mypy failed to narrow down union types including Self with isinstance #14912

Description

@mon-jai

Bug Report

mypy failed to narrow down union types including Self with isinstance.

To Reproduce

Consider the following code:

from dataclasses import dataclass
from typing import Self, reveal_type


@dataclass
class Foo:
    i: int

    def bar(self, other: Self | int) -> int:
        if isinstance(other, Foo):
            return self.i * other.i
        else:
            reveal_type(other)  # "int" expected, gets "Self | int"
            return self.i * other # Unsupported operand types for * ("int" and "Self")  [operator]mypy(error)

Expected Behavior

Other should be infered as an int and mypy reports no error.

Actual Behavior

mypy failed to narrow type of other

Revealed type is "Union[Self`0, builtins.int]"mypy(note)

Also, mypy reports the following error.

Unsupported operand types for * ("int" and "Self")  [operator]mypy(error)

Your Environment

  • Mypy version used: 1.1.1
  • Mypy command-line flags: --follow-imports=silent --ignore-missing-imports --show-column-numbers --no-pretty (VSCode defaults)
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11.1

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions