Skip to content

Commit

Permalink
Fix type object with type var default in union context
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
JukkaL committed Oct 18, 2024
1 parent 8150b51 commit 2a644b4
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 @@ -399,8 +399,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 @@ -6617,3 +6617,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 2a644b4

Please sign in to comment.