Skip to content

Commit fce2baf

Browse files
committed
Extract functions to module level, add lost get_proper_type
1 parent b747c02 commit fce2baf

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

mypy/constraints.py

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -344,18 +344,6 @@ def _infer_constraints(
344344
# This makes our constraint solver choke on type[T] <: type[A] | type[B],
345345
# solving T as generic meet(A, B) which is often `object`. Force unwrap such unions
346346
# if both sides are type[...] or unions thereof. See `testTypeVarType` test
347-
def _is_type_type(tp: ProperType) -> TypeGuard[TypeType | UnionType]:
348-
return (
349-
isinstance(tp, TypeType)
350-
or isinstance(tp, UnionType)
351-
and all(isinstance(get_proper_type(o), TypeType) for o in tp.items)
352-
)
353-
354-
def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType:
355-
if isinstance(tp, TypeType):
356-
return tp.item
357-
return UnionType.make_union([cast(TypeType, o).item for o in tp.items])
358-
359347
if _is_type_type(template) and _is_type_type(actual):
360348
template = _unwrap_type_type(template)
361349
actual = _unwrap_type_type(actual)
@@ -431,6 +419,30 @@ def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType:
431419
return template.accept(ConstraintBuilderVisitor(actual, direction, skip_neg_op))
432420

433421

422+
def _is_type_type(tp: ProperType) -> TypeGuard[TypeType | UnionType]:
423+
"""Is ``tp`` a type[...] or union thereof?
424+
425+
Type[A | B] is internally represented as type[A] | type[B], and this troubles
426+
the solver sometimes.
427+
"""
428+
return (
429+
isinstance(tp, TypeType)
430+
or isinstance(tp, UnionType)
431+
and all(isinstance(get_proper_type(o), TypeType) for o in tp.items)
432+
)
433+
434+
435+
def _unwrap_type_type(tp: TypeType | UnionType) -> ProperType:
436+
"""Rewrite `type[A] | type[B]` as `type[A | B]`.
437+
438+
This is an opposite of normalized form used elsewhere, necessary to solve type[...]
439+
constraints on typevars.
440+
"""
441+
if isinstance(tp, TypeType):
442+
return tp.item
443+
return UnionType.make_union([cast(TypeType, get_proper_type(o)).item for o in tp.items])
444+
445+
434446
def infer_constraints_if_possible(
435447
template: Type, actual: Type, direction: int
436448
) -> list[Constraint] | None:

0 commit comments

Comments
 (0)