Skip to content

Commit 2a644b4

Browse files
committed
Fix type object with type var default in union context
Union type context wasn's handled previously, and it triggered false positives, but apparently only if a type object had type var defaults. Fixes #17942.
1 parent 8150b51 commit 2a644b4

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

mypy/checkexpr.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,8 @@ def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
399399
# TODO: always do this in type_object_type by passing the original context
400400
result.ret_type.line = e.line
401401
result.ret_type.column = e.column
402-
if isinstance(get_proper_type(self.type_context[-1]), TypeType):
403-
# This is the type in a Type[] expression, so substitute type
402+
if is_type_type_context(self.type_context[-1]):
403+
# This is the type in a type[] expression, so substitute type
404404
# variables with Any.
405405
result = erasetype.erase_typevars(result)
406406
elif isinstance(node, MypyFile):
@@ -6617,3 +6617,12 @@ def get_partial_instance_type(t: Type | None) -> PartialType | None:
66176617
if t is None or not isinstance(t, PartialType) or t.type is None:
66186618
return None
66196619
return t
6620+
6621+
6622+
def is_type_type_context(context: Type | None) -> bool:
6623+
context = get_proper_type(context)
6624+
if isinstance(context, TypeType):
6625+
return True
6626+
if isinstance(context, UnionType):
6627+
return any(is_type_type_context(item) for item in context.items)
6628+
return False

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

Lines changed: 12 additions & 0 deletions
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)