MCPcopy Index your code
hub / github.com/python/mypy / visit_dict_expr

Method visit_dict_expr

mypy/checkexpr.py:5450–5531  ·  view source on GitHub ↗

Type check a dict expression. Translate it into a call to dict(), with provisions for **expr.

(self, e: DictExpr)

Source from the content-addressed store, hash-verified

5448 return typeddict_context.copy_modified()
5449
5450 def visit_dict_expr(self, e: DictExpr) -> Type:
5451 """Type check a dict expression.
5452
5453 Translate it into a call to dict(), with provisions for **expr.
5454 """
5455 # if the dict literal doesn't match TypedDict, check_typeddict_call_with_dict reports
5456 # an error, but returns the TypedDict type that matches the literal it found
5457 # that would cause a second error when that TypedDict type is returned upstream
5458 # to avoid the second error, we always return TypedDict type that was requested
5459 typeddict_contexts, exhaustive = self.find_typeddict_context(self.type_context[-1], e)
5460 if typeddict_contexts:
5461 if len(typeddict_contexts) == 1 and exhaustive:
5462 return self.check_typeddict_literal_in_context(e, typeddict_contexts[0])
5463 # Multiple items union, check if at least one of them matches cleanly.
5464 for typeddict_context in typeddict_contexts:
5465 with self.msg.filter_errors() as err, self.chk.local_type_map as tmap:
5466 ret_type = self.check_typeddict_literal_in_context(e, typeddict_context)
5467 if err.has_new_errors():
5468 continue
5469 self.chk.store_types(tmap)
5470 return ret_type
5471 # No item matched without an error, so we can't unambiguously choose the item.
5472 if exhaustive:
5473 self.msg.typeddict_context_ambiguous(typeddict_contexts, e)
5474
5475 # fast path attempt
5476 dt = self.fast_dict_type(e)
5477 if dt:
5478 return dt
5479
5480 # Define type variables (used in constructors below).
5481 kt = TypeVarType(
5482 "KT",
5483 "KT",
5484 id=TypeVarId(-1, namespace="<dict>"),
5485 values=[],
5486 upper_bound=self.object_type(),
5487 default=AnyType(TypeOfAny.from_omitted_generics),
5488 )
5489 vt = TypeVarType(
5490 "VT",
5491 "VT",
5492 id=TypeVarId(-2, namespace="<dict>"),
5493 values=[],
5494 upper_bound=self.object_type(),
5495 default=AnyType(TypeOfAny.from_omitted_generics),
5496 )
5497
5498 # Collect function arguments, watching out for **expr.
5499 args: list[Expression] = []
5500 expected_types: list[Type] = []
5501 for key, value in e.items:
5502 if key is None:
5503 args.append(value)
5504 expected_types.append(
5505 self.chk.named_generic_type("_typeshed.SupportsKeysAndGetItem", [kt, vt])
5506 )
5507 else:

Callers

nothing calls this directly

Calls 15

fast_dict_typeMethod · 0.95
object_typeMethod · 0.95
named_typeMethod · 0.95
check_callMethod · 0.95
TypeVarTypeClass · 0.90
TypeVarIdClass · 0.90
AnyTypeClass · 0.90
TupleExprClass · 0.90
TupleTypeClass · 0.90
CallableTypeClass · 0.90

Tested by

no test coverage detected