GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — blocker: https://github.com/python/mypy/issues/19560 · randolf-scholz/mypy@91cde69

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • mypy
    • checkexpr.py
    • infer.py
  • test-data/unit
    • check-expressions.test
    • check-inference.test
    • check-literal.test
    • check-recursive-types.test
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎mypy/checkexpr.py‎

Copy file name to clipboardExpand all lines: mypy/checkexpr.py
+108-91Lines changed: 108 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
CONTRAVARIANT,
5555
COVARIANT,
5656
IMPLICITLY_ABSTRACT,
57+
INVARIANT,
5758
LAMBDA_NAME,
5859
LITERAL_TYPE,
5960
REVEAL_LOCALS,
@@ -292,9 +293,9 @@ class ExpressionChecker(ExpressionVisitor[Type], ExpressionCheckerSharedApi):
292293
msg: MessageBuilder
293294
# Type context for type inference
294295
type_context: list[Type | None]
296+
expr_context: list[Expression]
295297
# constraints for the type context, used for type inference
296298
constraint_context: list[list[Constraint]]
297-
callee_context: list[CallableType]
298299

299300
# cache resolved types in some cases
300301
resolved_type: dict[Expression, ProperType]
@@ -322,6 +323,7 @@ def __init__(
322323
self.in_expression = False
323324
self.type_context = [None]
324325
self.constraint_context = [[]]
326+
self.expr_context = []
325327

326328
# Temporary overrides for expression types. This is currently
327329
# used by the union math in overloads.
@@ -1590,6 +1592,15 @@ def check_call(
15901592
if overloaded_result is not None:
15911593
return overloaded_result
15921594

1595+
_show(
1596+
f"\n=== CHECKING ==================="
1597+
f"\n\tcallee={callee}"
1598+
f"\n\targs={args} "
1599+
f"\n\targ_kinds={arg_kinds}"
1600+
f"\n\ttype_context={self.type_context}"
1601+
f"\n\tconstraints={self.constraint_context}"
1602+
)
1603+
15931604
result = self.check_callable_call(
15941605
callee,
15951606
args,
@@ -1602,11 +1613,6 @@ def check_call(
16021613
)
16031614
_show(
16041615
f"\n=== RESULT ==================="
1605-
f"\n\tcallee={callee}"
1606-
f"\n\targs={args} "
1607-
f"\n\targ_kinds={arg_kinds}"
1608-
f"\n\ttype_context={self.type_context}"
1609-
f"\n\tconstraints={self.constraint_context}"
16101616
f"\n\n\tret_type={result[0]}"
16111617
f"\n\tinferred_callee={result[1]}"
16121618
)
@@ -2053,6 +2059,9 @@ def infer_constraints_from_context(
20532059
# variables in an expression are inferred at the same time.
20542060
# (And this is hard, also we need to be careful with lambdas that require
20552061
# two passes.)
2062+
ctx = proper_ctx
2063+
ctx = update_type_context_using_constraints(ctx, self.constraint_context[-1])
2064+
20562065
if (
20572066
isinstance(proper_ret, TypeVarType)
20582067
or isinstance(proper_ret, UnionType)
@@ -2084,61 +2093,7 @@ def infer_constraints_from_context(
20842093
if not is_generic_instance(ctx) and not is_literal_type_like(ctx):
20852094
return []
20862095

2087-
NEW_CODE: bool = True
2088-
if NEW_CODE:
2089-
object_type = self.named_type("builtins.object")
2090-
ctx = proper_ctx
2091-
ctx = self.update_type_context_using_constraints(ctx)
2092-
return infer_constraints(proper_ret, ctx, SUBTYPE_OF)
2093-
else:
2094-
erased_ctx = get_proper_type(replace_meta_vars(ctx, ErasedType()))
2095-
return infer_constraints(proper_ret, erased_ctx, SUBTYPE_OF)
2096-
2097-
def update_type_context_using_constraints(self, ctx: Type | None) -> Type | None:
2098-
object_type = self.named_type("builtins.object")
2099-
if ctx is None:
2100-
return None
2101-
2102-
tvars = get_all_type_vars(ctx)
2103-
2104-
# concatenate self.constraint_context, which is a list of lists
2105-
all_constraints = [c for cl in self.constraint_context for c in cl]
2106-
upper_bounds = get_upper_bounds(tvars, all_constraints)
2107-
lower_bounds = get_lower_bounds(tvars, all_constraints)
2108-
2109-
for tvar in tvars:
2110-
if not tvar.id.is_meta_var():
2111-
continue
2112-
2113-
if isinstance(tvar, TypeVarType):
2114-
variance = infer_variance_in_expr(ctx, tvar)
2115-
if variance == COVARIANT:
2116-
# If the upper bound is just object, erase it instead.
2117-
# otherwise the solver may infer too general type
2118-
contextual_upper_bound = upper_bounds[tvar.id]
2119-
if is_same_type(contextual_upper_bound, object_type):
2120-
pass
2121-
ctx = replace_typevar(ctx, tvar.id, ErasedType())
2122-
else:
2123-
ctx = replace_typevar(ctx, tvar.id, contextual_upper_bound)
2124-
elif variance == CONTRAVARIANT:
2125-
contextual_lower_bound = lower_bounds[tvar.id]
2126-
2127-
ctx = replace_typevar(ctx, tvar.id, contextual_lower_bound)
2128-
2129-
# if is_same_type(contextual_lower_bound, UninhabitedType()):
2130-
# pass
2131-
# ctx = replace_typevar(ctx, tvar.id, ErasedType())
2132-
# else:
2133-
# ctx = replace_typevar(ctx, tvar.id, contextual_lower_bound)
2134-
else:
2135-
pass
2136-
ctx = replace_typevar(ctx, tvar.id, ErasedType())
2137-
else:
2138-
pass
2139-
ctx = replace_typevar(ctx, tvar.id, ErasedType())
2140-
2141-
return ctx
2096+
return infer_constraints(proper_ret, ctx, SUBTYPE_OF)
21422097

21432098
def infer_function_type_arguments(
21442099
self,
@@ -2159,32 +2114,31 @@ def infer_function_type_arguments(
21592114
if self.chk.in_checked_function():
21602115
# compute the outer solution
21612116
outer_constraints = self.infer_constraints_from_context(callee_type, context)
2117+
minimize = True
2118+
maximize = False
2119+
# detect if we are in an outermost call context.
2120+
# if len(self.type_context) >=2 and self.type_context[-2] is None and self.type_context[-1] is not None:
2121+
# minimize = False
2122+
# maximize = True
2123+
# if len(self.type_context) >= 2 and self.type_context[-2] is None and self.type_context[-1] is not None:
2124+
# minimize = False
2125+
# maximize = True
2126+
21622127
outer_solution, _ = solve_constraints(
21632128
callee_type.variables,
21642129
outer_constraints, # + self.constraint_context[-1],
21652130
strict=self.chk.in_checked_function(),
21662131
allow_polymorphic=False,
2132+
minimize=minimize,
2133+
maximize=maximize,
21672134
)
21682135
outer_solution = filter_solution(outer_solution)
21692136
outer_callee = self.apply_generic_arguments(
21702137
callee_type, outer_solution, context, skip_unsatisfied=True
21712138
)
21722139

21732140
# compute the trivial constraints
2174-
# each TVar is a subtype of its upper bound
2175-
trivial_constraints = [
2176-
Constraint(t, SUBTYPE_OF, t.upper_bound)
2177-
for t in callee_type.variables
2178-
if isinstance(t, TypeVarType)
2179-
]
2180-
# a constrained TVar is a subtype of the union of its values
2181-
# relevant for `testCallGenericFunctionWithTypeVarValueRestrictionUsingContext`
2182-
trivial_constraints += [
2183-
Constraint(t, SUBTYPE_OF, make_simplified_union(t.values))
2184-
for t in callee_type.variables
2185-
if isinstance(t, TypeVarType) and t.values
2186-
]
2187-
# trivial_constraints = []
2141+
trivial_constraints = get_trivial_constraints(callee_type.variables)
21882142

21892143
# _show(
21902144
# f"\n=== DEBUG ============================"
@@ -2213,6 +2167,12 @@ def infer_function_type_arguments(
22132167
# relevant for `testWideOuterContext` unit tests.
22142168
constraints=outer_constraints + trivial_constraints,
22152169
)
2170+
_show(
2171+
f"\n===== INFERRED ARGS ====="
2172+
f"\n\t{callee_type.arg_types}"
2173+
f"\n\tconstraints={outer_constraints + trivial_constraints}"
2174+
f"\n\t{arg_types=}"
2175+
)
22162176

22172177
arg_pass_nums = self.get_arg_infer_passes(
22182178
callee_type, args, arg_types, formal_to_actual, len(args)
@@ -2251,8 +2211,8 @@ def infer_function_type_arguments(
22512211
# HACK: convert "Literal?" constraints to their non-literal versions.
22522212
# relevant for `testLiteral*` tests.
22532213
inner_constraints = [
2254-
Constraint(c.original_type_var, c.op, forget_last_known_value(c.target))
2255-
# Constraint(c.original_type_var, c.op, use_last_known_value(c.target))
2214+
# Constraint(c.original_type_var, c.op, forget_last_known_value(c.target))
2215+
Constraint(c.original_type_var, c.op, c.target)
22562216
for c in _inner_constraints
22572217
]
22582218
inner_solution, _ = solve_constraints(
@@ -2285,6 +2245,14 @@ def infer_function_type_arguments(
22852245
callee_type, joint_solution, context, skip_unsatisfied=True
22862246
)
22872247

2248+
# determine if solution was successful:
2249+
if is_proper_solution(callee_type, joint_solution):
2250+
extra_constraints = outer_constraints + inner_constraints + trivial_constraints
2251+
elif is_proper_solution(callee_type, outer_solution):
2252+
extra_constraints = outer_constraints + trivial_constraints
2253+
else:
2254+
extra_constraints = outer_constraints + inner_constraints
2255+
22882256
# determine which solution to take
22892257
use_joint = all(
22902258
# only use joint if it solved at least the same variables as the outer solution
@@ -2392,7 +2360,7 @@ def infer_function_type_arguments(
23922360
minimize=True,
23932361
)
23942362
inferred_args = filter_solution(new_inner_solution)
2395-
# _show(f"Two stage inference: \n\t{callee_type=}\n\t{inferred_args=}")
2363+
# _show(f"Two stage inference: \n\t{callee_type=}\n\t{inferred_args=}")
23962364
else: # END NEW CODE
23972365
pass
23982366

@@ -2435,11 +2403,8 @@ def infer_function_type_arguments(
24352403
elif not first_arg or not is_subtype(self.named_type("builtins.str"), first_arg):
24362404
self.chk.fail(message_registry.KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE, context)
24372405

2438-
if not self.chk.options.old_type_inference and any(
2439-
a is None
2440-
or isinstance(get_proper_type(a), UninhabitedType)
2441-
or set(get_type_vars(a)) & set(callee_type.variables)
2442-
for a in inferred_args
2406+
if not self.chk.options.old_type_inference and not is_proper_solution(
2407+
callee_type, inferred_args
24432408
):
24442409
if need_refresh:
24452410
# Technically we need to refresh formal_to_actual after *each* inference pass,
@@ -2465,6 +2430,8 @@ def infer_function_type_arguments(
24652430
context=self.argument_infer_context(),
24662431
strict=self.chk.in_checked_function(),
24672432
allow_polymorphic=True,
2433+
extra_constraints=extra_constraints,
2434+
minimize=True,
24682435
)
24692436
poly_callee_type = self.apply_generic_arguments(
24702437
callee_type, poly_inferred_args, context
@@ -6315,6 +6282,7 @@ def accept(
63156282
self.constraint_context.append(constraints or [])
63166283
# type_context = self.update_type_context_using_constraints(type_context)
63176284
self.type_context.append(type_context)
6285+
self.expr_context.append(node)
63186286

63196287
# fix the type context using the contextual constraints
63206288
if HACKS and type_context is not None:
@@ -6381,6 +6349,7 @@ def accept(
63816349
)
63826350
self.is_callee = old_is_callee
63836351
self.type_context.pop()
6352+
self.expr_context.pop()
63846353
self.constraint_context.pop()
63856354
assert typ is not None
63866355
self.chk.store_type(node, typ)
@@ -7151,21 +7120,25 @@ def _show(*args: object) -> None:
71517120

71527121

71537122
def get_trivial_constraints(
7154-
tvars: Sequence[TypeVarLikeType], filter_object: bool = True
7123+
tvars: Sequence[TypeVarLikeType], /, *, filter_object: bool = True
71557124
) -> Sequence[Constraint]:
71567125
"""Every Type Variable is a subtype of its upper bound."""
71577126
# each TVar is a subtype of its upper bound
71587127
constraints: list[Constraint] = []
71597128
for t in tvars:
71607129
upper_bound = get_proper_type(t.upper_bound)
7130+
7131+
# An upper bound of 'object' is not informative, and usually just means no
7132+
# constraint was specified. We skip these because the solver picks the upper
7133+
# bound as a solution if there are no lower constraints.
71617134
if (
71627135
filter_object
71637136
and isinstance(upper_bound, Instance)
71647137
and upper_bound.type.fullname == "builtins.object"
71657138
):
7166-
# these are usually because no constraint was specified, not because the user gave one.
7167-
continue
7168-
constraints.append(Constraint(t, SUBTYPE_OF, upper_bound))
7139+
pass
7140+
else:
7141+
constraints.append(Constraint(t, SUBTYPE_OF, upper_bound))
71697142

71707143
if isinstance(t, TypeVarType) and t.values:
71717144
constraints.append(Constraint(t, SUBTYPE_OF, make_simplified_union(t.values)))
@@ -7183,10 +7156,6 @@ def get_upper_bounds(
71837156
relevant_constraints = [
71847157
c for c in constraints if c.type_var == tvar.id and c.op == SUBTYPE_OF
71857158
]
7186-
# if not relevant_constraints:
7187-
# upper_bounds[tvar.id] = None
7188-
# continue
7189-
71907159
top = tvar.upper_bound
71917160
for c in relevant_constraints:
71927161
top = meet_types(top, c.target)
@@ -7212,3 +7181,51 @@ def get_lower_bounds(
72127181
bottom = join_types(bottom, c.target)
72137182
lower_bounds[tvar.id] = bottom
72147183
return lower_bounds
7184+
7185+
7186+
def update_type_context_using_constraints(typ: Type, /, constraints: list[Constraint]) -> Type:
7187+
tvars = get_all_type_vars(typ)
7188+
7189+
# concatenate self.constraint_context, which is a list of lists
7190+
upper_bounds = get_upper_bounds(tvars, constraints)
7191+
lower_bounds = get_lower_bounds(tvars, constraints)
7192+
7193+
for tvar in tvars:
7194+
if not tvar.id.is_meta_var():
7195+
continue
7196+
7197+
if isinstance(tvar, TypeVarType):
7198+
variance = infer_variance_in_expr(typ, tvar)
7199+
7200+
if variance == INVARIANT:
7201+
typ = replace_typevar(typ, tvar.id, ErasedType())
7202+
7203+
elif variance == COVARIANT:
7204+
contextual_upper_bound = upper_bounds[tvar.id]
7205+
typ = replace_typevar(typ, tvar.id, contextual_upper_bound)
7206+
7207+
elif variance == CONTRAVARIANT:
7208+
contextual_lower_bound = lower_bounds[tvar.id]
7209+
typ = replace_typevar(typ, tvar.id, contextual_lower_bound)
7210+
7211+
else:
7212+
raise ValueError(f"Unexpected variance: {variance}")
7213+
7214+
elif isinstance(tvar, TypeVarTupleType):
7215+
typ = replace_typevar(typ, tvar.id, ErasedType())
7216+
elif isinstance(tvar, ParamSpecType):
7217+
typ = replace_typevar(typ, tvar.id, ErasedType())
7218+
else:
7219+
# Add other branches if more TypeVarLikeType are added
7220+
raise TypeError(f"Unexpected type variable type: {tvar}")
7221+
7222+
return typ
7223+
7224+
7225+
def is_proper_solution(callee_type: CallableType, inferred_args: Sequence[Type | None]) -> bool:
7226+
return not any(
7227+
a is None
7228+
or isinstance(get_proper_type(a), UninhabitedType)
7229+
or (set(get_type_vars(a)) & set(callee_type.variables))
7230+
for a in inferred_args
7231+
)
Collapse file

‎mypy/infer.py‎

Copy file name to clipboardExpand all lines: mypy/infer.py
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from mypy.constraints import (
99
SUBTYPE_OF,
1010
SUPERTYPE_OF,
11+
Constraint,
1112
infer_constraints,
1213
infer_constraints_for_callable,
1314
)
@@ -39,6 +40,8 @@ def infer_function_type_arguments(
3940
context: ArgumentInferContext,
4041
strict: bool = True,
4142
allow_polymorphic: bool = False,
43+
extra_constraints: list[Constraint | None] = None,
44+
minimize: bool = False,
4245
) -> tuple[list[Type | None], list[TypeVarLikeType]]:
4346
"""Infer the type arguments of a generic function.
4447
@@ -58,9 +61,12 @@ def infer_function_type_arguments(
5861
callee_type, arg_types, arg_kinds, arg_names, formal_to_actual, context
5962
)
6063

64+
if extra_constraints:
65+
constraints += extra_constraints
66+
6167
# Solve constraints.
6268
type_vars = callee_type.variables
63-
return solve_constraints(type_vars, constraints, strict, allow_polymorphic)
69+
return solve_constraints(type_vars, constraints, strict, allow_polymorphic, minimize=minimize)
6470

6571

6672
def infer_type_arguments(

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.