Skip to content

Commit 71e1f05

Browse files
JukkaLhauntsaninja
authored andcommitted
Fix type object with type var default in union context (#17991)
Union type context wasn't handled previously, and it triggered false positives, but apparently only if a type object had type var defaults. Fixes #17942.
1 parent 34d8603 commit 71e1f05

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

mypy/checkexpr.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,8 @@ def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
396396
# TODO: always do this in type_object_type by passing the original context
397397
result.ret_type.line = e.line
398398
result.ret_type.column = e.column
399-
if isinstance(get_proper_type(self.type_context[-1]), TypeType):
400-
# This is the type in a Type[] expression, so substitute type
399+
if is_type_type_context(self.type_context[-1]):
400+
# This is the type in a type[] expression, so substitute type
401401
# variables with Any.
402402
result = erasetype.erase_typevars(result)
403403
elif isinstance(node, MypyFile):
@@ -6592,3 +6592,12 @@ def get_partial_instance_type(t: Type | None) -> PartialType | None:
65926592
if t is None or not isinstance(t, PartialType) or t.type is None:
65936593
return None
65946594
return t
6595+
6596+
6597+
def is_type_type_context(context: Type | None) -> bool:
6598+
context = get_proper_type(context)
6599+
if isinstance(context, TypeType):
6600+
return True
6601+
if isinstance(context, UnionType):
6602+
return any(is_type_type_context(item) for item in context.items)
6603+
return False

test-data/unit/check-typevar-defaults.test

+12
Original file line numberDiff line numberDiff line change
@@ -717,3 +717,15 @@ def func_d3(
717717
reveal_type(c) # N: Revealed type is "__main__.B[__main__.A[builtins.dict[builtins.int, builtins.float]]]"
718718
reveal_type(d) # N: Revealed type is "__main__.B[builtins.int]"
719719
[builtins fixtures/dict.pyi]
720+
721+
[case testTypeVarDefaultsAndTypeObjectTypeInUnion]
722+
from __future__ import annotations
723+
from typing import Generic
724+
from typing_extensions import TypeVar
725+
726+
_I = TypeVar("_I", default=int)
727+
728+
class C(Generic[_I]): pass
729+
730+
t: type[C] | int = C
731+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)