diff --git a/mypy/checker.py b/mypy/checker.py index 8775f1ddef29..4799f255af93 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -6901,6 +6901,14 @@ def narrow_type_by_identity_equality( expr_in_type_expr = type_expr.expr else: continue + + p_expr_type = get_proper_type(operand_types[i]) + if isinstance(p_expr_type, TypeType) and isinstance(p_expr_type.item, TypeVarType): + # This mirrors logic in comparison_type_narrowing_helper + # In theory, this is like `i not in narrowable_indices`, except that + # narrowable_indices filters all type(x) narrowing as it's a call + continue + for j in expr_indices: if i == j: continue diff --git a/test-data/unit/check-narrowing.test b/test-data/unit/check-narrowing.test index 982a86e38edd..154e283daa2d 100644 --- a/test-data/unit/check-narrowing.test +++ b/test-data/unit/check-narrowing.test @@ -3395,6 +3395,30 @@ def f(x: str, y: Any, z: object): reveal_type(z) # N: Revealed type is "builtins.str" [builtins fixtures/primitives.pyi] +[case testTypeEqualsCheckWideningSelf] +# flags: --strict-equality --warn-unreachable +from typing import Any +from typing_extensions import Self + +class A: + def f(self: Self, y: Any, z: object): + if type(self) is type(y): + reveal_type(self) # N: Revealed type is "Self`0" + reveal_type(y) # N: Revealed type is "Self`0" + + if type(self) is type(z): + reveal_type(self) # N: Revealed type is "Self`0" + reveal_type(z) # N: Revealed type is "Self`0" + + if type(self) == type(y): + reveal_type(self) # N: Revealed type is "Self`0" + reveal_type(y) # N: Revealed type is "Self`0" + + if type(self) == type(z): + reveal_type(self) # N: Revealed type is "Self`0" + reveal_type(z) # N: Revealed type is "Self`0" +[builtins fixtures/primitives.pyi] + [case testTypeEqualsCheckUsingIs] # flags: --strict-equality --warn-unreachable from typing import Any