Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6568,6 +6568,7 @@ def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMa
isinstance(p_expr := get_proper_type(expr_type), CallableType)
and p_expr.is_type_obj()
)
and not isinstance(p_expr, TypeType)
):
h = literal_hash(expr)
if h is not None:
Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -2920,3 +2920,23 @@ def f2(x: Any) -> None:
return
reveal_type(x) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]

[case testNarrowTypeVarType]
from typing import TypeVar

T = TypeVar("T")

class A: ...

def foo(X: type[T]) -> T:
if X == A:
return X()
raise

# It could be nice to make these two test cases consistent, but it would be tricky
# The above case is much more common in real world code
def bar(X: type[T]) -> T:
if X == A:
return A() # E: Incompatible return value type (got "A", expected "T")
raise
[builtins fixtures/type.pyi]
1 change: 1 addition & 0 deletions test-data/unit/fixtures/type.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ S = TypeVar("S")
class object:
def __init__(self) -> None: pass
def __str__(self) -> 'str': pass
def __eq__(self, value: object, /) -> bool: ...

class list(Generic[T]): pass

Expand Down