Skip to content

Commit 1c8850d

Browse files
committed
Avoid narrowing TypeType
This relates to changes made in python#20492
1 parent f920a2f commit 1c8850d

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

mypy/checker.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6476,6 +6476,7 @@ def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMa
64766476
isinstance(p_expr := get_proper_type(expr_type), CallableType)
64776477
and p_expr.is_type_obj()
64786478
)
6479+
and not isinstance(p_expr, TypeType)
64796480
):
64806481
h = literal_hash(expr)
64816482
if h is not None:

test-data/unit/check-narrowing.test

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2928,3 +2928,23 @@ def f2(x: Any) -> None:
29282928
return
29292929
reveal_type(x) # N: Revealed type is "Any"
29302930
[builtins fixtures/tuple.pyi]
2931+
2932+
[case testNarrowTypeVarType]
2933+
from typing import TypeVar
2934+
2935+
T = TypeVar("T")
2936+
2937+
class A: ...
2938+
2939+
def foo(X: type[T]) -> T:
2940+
if X == A:
2941+
return X()
2942+
raise
2943+
2944+
# It could be nice to make these two test cases consistent, but it would be tricky
2945+
# The above case is much more common in real world code
2946+
def bar(X: type[T]) -> T:
2947+
if X == A:
2948+
return A() # E: Incompatible return value type (got "A", expected "T")
2949+
raise
2950+
[builtins fixtures/type.pyi]

test-data/unit/fixtures/type.pyi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ S = TypeVar("S")
1010
class object:
1111
def __init__(self) -> None: pass
1212
def __str__(self) -> 'str': pass
13+
def __eq__(self, value: object, /) -> bool: ...
1314

1415
class list(Generic[T]): pass
1516

0 commit comments

Comments
 (0)