Skip to content

Commit b5e7793

Browse files
committed
Avoid narrowing type[T] in type calls
Similar to #20662
1 parent a7bdffd commit b5e7793

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

mypy/checker.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6901,6 +6901,14 @@ def narrow_type_by_identity_equality(
69016901
expr_in_type_expr = type_expr.expr
69026902
else:
69036903
continue
6904+
6905+
p_expr_type = get_proper_type(operand_types[i])
6906+
if isinstance(p_expr_type, TypeType) and isinstance(p_expr_type.item, TypeVarType):
6907+
# This mirrors logic in comparison_type_narrowing_helper
6908+
# In theory, this is like `i not in narrowable_indices`, except that
6909+
# narrowable_indices filters all type(x) narrowing as it's a call
6910+
continue
6911+
69046912
for j in expr_indices:
69056913
if i == j:
69066914
continue

test-data/unit/check-narrowing.test

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3395,6 +3395,30 @@ def f(x: str, y: Any, z: object):
33953395
reveal_type(z) # N: Revealed type is "builtins.str"
33963396
[builtins fixtures/primitives.pyi]
33973397

3398+
[case testTypeEqualsCheckWideningSelf]
3399+
# flags: --strict-equality --warn-unreachable
3400+
from typing import Any
3401+
from typing_extensions import Self
3402+
3403+
class A:
3404+
def f(self: Self, y: Any, z: object):
3405+
if type(self) is type(y):
3406+
reveal_type(self) # N: Revealed type is "Self`0"
3407+
reveal_type(y) # N: Revealed type is "Self`0"
3408+
3409+
if type(self) is type(z):
3410+
reveal_type(self) # N: Revealed type is "Self`0"
3411+
reveal_type(z) # N: Revealed type is "Self`0"
3412+
3413+
if type(self) == type(y):
3414+
reveal_type(self) # N: Revealed type is "Self`0"
3415+
reveal_type(y) # N: Revealed type is "Self`0"
3416+
3417+
if type(self) == type(z):
3418+
reveal_type(self) # N: Revealed type is "Self`0"
3419+
reveal_type(z) # N: Revealed type is "Self`0"
3420+
[builtins fixtures/primitives.pyi]
3421+
33983422
[case testTypeEqualsCheckUsingIs]
33993423
# flags: --strict-equality --warn-unreachable
34003424
from typing import Any

0 commit comments

Comments
 (0)