Skip to content

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

Closed

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

  1. mon-jai commented on Mar 17, 2023

    @mon-jai
    Author

    isinstance(other, self.__class__) doesn't work too.

  2. tyralla commented on Mar 18, 2023

    @tyralla
    Collaborator

    Simpler repro:

    [case testNarrowSelfType]
    from typing import Self, Union
    class A: ...
    class B:
        def f(self, v: Union[Self, A]) -> A:
            if isinstance(v, B):
                return A()
            else:
                return v  # false error: Incompatible return value type (got "Union[Self, A]", expected "A")
    [builtins fixtures/isinstancelist.pyi]
  3. added a commit that references this issue on Mar 25, 2023
    c5ddc36
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