Skip to content

Commit 8dad976

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

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-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: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3395,6 +3395,33 @@ 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 __init__(self, x: int):
3405+
self.x = x
3406+
3407+
def f(self: Self, y: Any, z: object):
3408+
if type(self) is type(y):
3409+
reveal_type(self) # N: Revealed type is "Self`0"
3410+
reveal_type(y) # N: Revealed type is "Self`0"
3411+
3412+
if type(self) is type(z):
3413+
reveal_type(self) # N: Revealed type is "Self`0"
3414+
reveal_type(z) # N: Revealed type is "Self`0"
3415+
3416+
if type(self) == type(y):
3417+
reveal_type(self) # N: Revealed type is "Self`0"
3418+
reveal_type(y) # N: Revealed type is "Self`0"
3419+
3420+
if type(self) == type(z):
3421+
reveal_type(self) # N: Revealed type is "Self`0"
3422+
reveal_type(z) # N: Revealed type is "Self`0"
3423+
[builtins fixtures/primitives.pyi]
3424+
33983425
[case testTypeEqualsCheckUsingIs]
33993426
# flags: --strict-equality --warn-unreachable
34003427
from typing import Any

0 commit comments

Comments
 (0)