Skip to content

Check class object assignability and RHS __eq__ for overlap - #11931

Open
crypt0lith wants to merge 4 commits into
microsoft:mainfrom
crypt0lith:fix/type-comparable-to-instance
Open

crypt0lith wants to merge 4 commits into
microsoft:mainfrom
crypt0lith:fix/type-comparable-to-instance

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

x in (...) narrows the subject to Never when the container holds class objects and the subject is of type object or a protocol type, or when only the subject's class overrides __eq__. The branch is then unreachable, and reportUnnecessaryContains reports it. reportUnnecessaryComparison reports the same operand pairs in ==, and is with a class object on the left against an object or protocol subject.

# pyright: reportUnnecessaryComparison=true, reportUnnecessaryContains=true
from typing import Hashable


class A: ...


class B:
    def __eq__(self, other: object) -> bool:
        return True


def f(x: object, h: Hashable, a: A, b: B):
    if int == x:
        pass

    if h in (int, str):
        reveal_type(h)

    if a == b:
        pass

    if b in (a,):
        reveal_type(b)
:14:8 - error: Condition will always evaluate to False since the types "type[int]" and "object" have no overlap (reportUnnecessaryComparison)
:17:8 - error: Expression will always evaluate to False since the types "Hashable" and "type[int] | type[str]" have no overlap (reportUnnecessaryContains)
:20:8 - error: Condition will always evaluate to False since the types "A" and "B" have no overlap (reportUnnecessaryComparison)
:23:8 - error: Expression will always evaluate to False since the types "B" and "A" have no overlap (reportUnnecessaryContains)

Root cause

When the left operand is a class object, isTypeComparable checks assignability in either direction only if the right operand is also a class object or a type instance. With the operands swapped, the instance branch checks assignability against any class, so x == int is comparable while int == x isn't.

When assignability fails, both branches look for an __eq__ overload only on the left operand: on the metaclass of a class object, or on the class of an instance. Python falls back to the right operand's reflected __eq__ when the left one returns NotImplemented.

narrowTypeForContainerElementType passes the container element as the left operand.

Fix

Check assignability in either direction whenever the right operand is a class or class instance, as the instance branch does. Treat the operands as comparable when the right operand's class or metaclass overrides __eq__, except for is and is not, which never call __eq__, and except for an __eq__ declared on a built-in class, which returns NotImplemented for other types.

Test

Cases added to comparison2.py
Case Expected Description
func14 class object compared with a protocol or object instance
func15 error class object == unrelated class instance
func16 right operand's class or metaclass overrides __eq__
func17 error is with a right operand whose class overrides __eq__
func18 error right operand whose __eq__ is assigned through self
func19 error right operand whose __eq__ is inherited from a built-in class
Cases added to unnecessaryContains1.py
Case Expected Description
func6 object or protocol subject, class object elements
func7 error unrelated class subject, class object element
func8 subject whose class overrides __eq__, unrelated class element
Cases added to typeNarrowingIn1.py
Case Expected Description
func35 object subject narrows to the class objects in the container

When the left operand is a class object, isTypeComparable checks
assignability only against a class object or type instance on the
right, so a class object is never comparable to an object or protocol
instance. Check assignability whenever the right operand is a class or
class instance.
@heejaechang

Heejae Chang (heejaechang) commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 2baca801 — verdict: red

Automated CLI checks compared this change with its base revision.
34 focused check(s) completed.

Needs review: reportUnnecessaryComparison newly reported

The PR reports reportUnnecessaryComparison for this example; the base does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

main.py

from typing import Callable, assert_type
reveal_type(0)
class Parent:
    def __eq__(self, other: object) -> bool:
        return True
class Child(Parent):
    __eq__: Callable[[object], bool]
def compare(value: Child) -> bool:
    assert_type(value == 0, bool)
    return value == 0

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic",
  "reportUnnecessaryComparison": "error",
  "reportUnnecessaryContains": "error"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 227769493b2cd2fce5c82d3be42c769a947e0f70

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 2baca80105f0c40062360d942bad179eb2c83ddb

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Child\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          26
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Child\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          9,
          11
        ],
        "end": [
          9,
          21
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Additional reproduction: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Create these files in an empty directory:

annotation.py

from typing import Callable
reveal_type(0)
class Parent:
    def __eq__(self, other: object) -> bool:
        return True
class Child(Parent):
    __eq__: Callable[[object], bool]
def check(value: int, element: Child) -> None:
    if value in (element,):
        value.upper()  # ERR:reportAttributeAccessIssue

pyrightconfig.json

{
  "include": [
    "annotation.py",
    "slot.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic",
  "reportUnnecessaryComparison": "error",
  "reportUnnecessaryContains": "error"
}

slot.py

reveal_type(0)
class Slotted:
    __slots__ = ('__eq__',)
    def __init__(self) -> None:
        self.__eq__ = lambda other: True
def check(value: int, element: Slotted) -> None:
    if value in (element,):
        value.upper()  # ERR:reportAttributeAccessIssue

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 227769493b2cd2fce5c82d3be42c769a947e0f70

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "annotation.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"int\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          9,
          14
        ],
        "end": [
          9,
          19
        ]
      }
    },
    {
      "file": "annotation.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "slot.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"int\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          7,
          14
        ],
        "end": [
          7,
          19
        ]
      }
    },
    {
      "file": "slot.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 2baca80105f0c40062360d942bad179eb2c83ddb

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "annotation.py",
      "severity": "error",
      "rule": "reportUnnecessaryContains",
      "message": "Expression will always evaluate to False since the types \"int\" and \"Child\" have no overlap",
      "range": {
        "start": [
          8,
          7
        ],
        "end": [
          8,
          26
        ]
      }
    },
    {
      "file": "annotation.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "slot.py",
      "severity": "error",
      "rule": "reportUnnecessaryContains",
      "message": "Expression will always evaluate to False since the types \"int\" and \"Slotted\" have no overlap",
      "range": {
        "start": [
          6,
          7
        ],
        "end": [
          6,
          26
        ]
      }
    },
    {
      "file": "slot.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Additional reproduction: reportUnnecessaryComparison newly reported

The PR reports reportUnnecessaryComparison for this example; the base does not. Is this change intended?

Create these files in an empty directory:

classvars.py

from typing import Callable, ClassVar, assert_type
reveal_type(0)
def eq(self: object, other: object) -> bool:
    return True
class ClassVariable:
    __eq__: ClassVar[Callable[[object, object], bool]] = eq
class Default:
    __eq__ = eq
class AnnotatedDefault:
    __eq__: Callable[[object, object], bool] = eq
def check(a: ClassVariable, b: Default, c: AnnotatedDefault) -> None:
    assert_type(a == 0, bool)
    assert_type(0 == a, bool)
    assert_type(b == 0, bool)
    assert_type(0 == b, bool)
    assert_type(c == 0, bool)
    assert_type(0 == c, bool)

multiple.py

from typing import Callable, assert_type
reveal_type(0)
class Annotation:
    __eq__: Callable[[object], bool]
class Equality:
    def __eq__(self, other: object) -> bool:
        return True
class Before(Annotation, Equality): pass
class After(Equality, Annotation): pass
def check(first: Before, last: After) -> None:
    assert_type(first == 0, bool)
    assert_type(last == 0, bool)

pyrightconfig.json

{
  "include": [
    "multiple.py",
    "classvars.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic",
  "reportUnnecessaryComparison": "error",
  "reportUnnecessaryContains": "error"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 227769493b2cd2fce5c82d3be42c769a947e0f70

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "classvars.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "multiple.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 2baca80105f0c40062360d942bad179eb2c83ddb

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "classvars.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "multiple.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Before\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          26
        ]
      }
    },
    {
      "file": "multiple.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Additional reproduction: reportUnnecessaryComparison newly reported

The PR reports reportUnnecessaryComparison for this example; the base does not. Is this change intended?

Create these files in an empty directory:

annotations.py

from typing import Callable, Generic, TypeVar, assert_type
reveal_type(0)
T = TypeVar('T')
class Parent:
    def __eq__(self, other: object) -> bool:
        return True
class GenericChild(Parent, Generic[T]):
    __eq__: Callable[[object], bool]
    def read(self, value: T) -> T:
        return value
class Meta(type):
    def __eq__(self, other: object) -> bool:
        return True
class ChildMeta(Meta):
    __eq__: Callable[[object], bool]
class Value(metaclass=ChildMeta): pass
def check(a: GenericChild[str]) -> None:
    assert_type(a == 0, bool)
    assert_type(a.read('x'), str)
    assert_type(Value == 0, bool)

controls.py

from typing import Callable, ClassVar, assert_type
reveal_type(0)
class Parent:
    def __eq__(self, other: object) -> bool:
        return True
class Child(Parent):
    def __init__(self) -> None:
        self.__eq__ = lambda other: False
class Assigned:
    __eq__: Callable[[object, object], bool] = lambda self, other: True
class Static:
    @staticmethod
    def __eq__(other: object) -> bool:
        return True
def check(a: Child, b: Assigned, c: Static) -> None:
    assert_type(a == 0, bool)
    assert_type(b == 0, bool)
    assert_type(c == 0, bool)

pyrightconfig.json

{
  "include": [
    "annotations.py",
    "slots_inherited.py",
    "controls.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic",
  "reportUnnecessaryComparison": "error",
  "reportUnnecessaryContains": "error"
}

slots_inherited.py

from typing import assert_type
reveal_type(0)
class Slotted:
    __slots__ = ('__eq__',)
    def __init__(self) -> None:
        self.__eq__ = lambda other: True
class Child(Slotted):
    def read(self) -> str:
        return 'payload'
def check(value: Child) -> None:
    assert_type(value == 0, bool)
    if value in (0,):
        assert_type(value.read(), str)

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 227769493b2cd2fce5c82d3be42c769a947e0f70

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "annotations.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "controls.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "slots_inherited.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 2baca80105f0c40062360d942bad179eb2c83ddb

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "annotations.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"GenericChild[str]\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          17,
          16
        ],
        "end": [
          17,
          22
        ]
      }
    },
    {
      "file": "annotations.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"type[Value]\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          19,
          16
        ],
        "end": [
          19,
          26
        ]
      }
    },
    {
      "file": "annotations.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "controls.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "slots_inherited.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Child\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          26
        ]
      }
    },
    {
      "file": "slots_inherited.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Needs review: reportUnnecessaryComparison newly reported

The PR reports reportUnnecessaryComparison for this example; the base does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

main.py

from typing import assert_type
reveal_type(0)
class Slotted:
    __slots__ = ('__eq__',)
    def __init__(self) -> None:
        self.__eq__ = lambda other: True
def compare(value: Slotted) -> bool:
    assert_type(value == 0, bool)
    return value == 0

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic",
  "reportUnnecessaryComparison": "error",
  "reportUnnecessaryContains": "error"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 227769493b2cd2fce5c82d3be42c769a947e0f70

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 2baca80105f0c40062360d942bad179eb2c83ddb

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Slotted\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          26
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportUnnecessaryComparison",
      "message": "Condition will always evaluate to False since the types \"Slotted\" and \"Literal[0]\" have no overlap",
      "range": {
        "start": [
          8,
          11
        ],
        "end": [
          8,
          21
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@crypt0lith
crypt0lith force-pushed the fix/type-comparable-to-instance branch from 4982666 to d4acb4c Compare October 28, 2026 00:23
@crypt0lith crypt0lith changed the title Fix class objects compared as disjoint from object and protocol types Fix operand-order asymmetry in type comparison checks Oct 28, 2026
@crypt0lith
crypt0lith force-pushed the fix/type-comparable-to-instance branch from 1101ed2 to d995710 Compare November 11, 2026 02:43
@crypt0lith crypt0lith changed the title Fix operand-order asymmetry in type comparison checks Check class object assignability and RHS __eq__ for overlap Nov 13, 2026
@crypt0lith
crypt0lith force-pushed the fix/type-comparable-to-instance branch from 1ccec55 to 2baca80 Compare November 13, 2026 18:51
@bschnurr

Copy link
Copy Markdown
Member

Local review: 2baca801 integrated with ff00b031.

The older instance-field QA case no longer reproduces. Both operand orders still report reportUnnecessaryComparison when __eq__ exists only on the instance, while x == z with a real right-hand __eq__ method no longer gets the false positive. CPython 3.14 returned (False, False, True) for those three comparisons. All three focused tests passed.

@crypt0lith
crypt0lith force-pushed the fix/type-comparable-to-instance branch from 2baca80 to fe2f1bb Compare November 28, 2026 15:47
@crypt0lith

Copy link
Copy Markdown
Contributor Author

I dropped 2baca80. Main has the same instance-member defect in the left operand's __eq__ lookup and in isTypeHashable, so it's a separate issue. I've opened #12072 to track it and #12073 to close it.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants