Skip to content

Commit

Permalink
Fix type object with type var default in union context (python#17991)
Browse files Browse the repository at this point in the history
Union type context wasn't handled previously, and it triggered false
positives, but apparently only if a type object had type var defaults.

Fixes python#17942.
  • Loading branch information
JukkaL authored and hauntsaninja committed Oct 18, 2024
1 parent 34d8603 commit 71e1f05
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
13 changes: 11 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,8 @@ def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
# TODO: always do this in type_object_type by passing the original context
result.ret_type.line = e.line
result.ret_type.column = e.column
if isinstance(get_proper_type(self.type_context[-1]), TypeType):
# This is the type in a Type[] expression, so substitute type
if is_type_type_context(self.type_context[-1]):
# This is the type in a type[] expression, so substitute type
# variables with Any.
result = erasetype.erase_typevars(result)
elif isinstance(node, MypyFile):
Expand Down Expand Up @@ -6592,3 +6592,12 @@ def get_partial_instance_type(t: Type | None) -> PartialType | None:
if t is None or not isinstance(t, PartialType) or t.type is None:
return None
return t


def is_type_type_context(context: Type | None) -> bool:
context = get_proper_type(context)
if isinstance(context, TypeType):
return True
if isinstance(context, UnionType):
return any(is_type_type_context(item) for item in context.items)
return False
12 changes: 12 additions & 0 deletions test-data/unit/check-typevar-defaults.test
Original file line number Diff line number Diff line change
Expand Up @@ -717,3 +717,15 @@ def func_d3(
reveal_type(c) # N: Revealed type is "__main__.B[__main__.A[builtins.dict[builtins.int, builtins.float]]]"
reveal_type(d) # N: Revealed type is "__main__.B[builtins.int]"
[builtins fixtures/dict.pyi]

[case testTypeVarDefaultsAndTypeObjectTypeInUnion]
from __future__ import annotations
from typing import Generic
from typing_extensions import TypeVar

_I = TypeVar("_I", default=int)

class C(Generic[_I]): pass

t: type[C] | int = C
[builtins fixtures/tuple.pyi]

0 comments on commit 71e1f05

Please sign in to comment.