MCPcopy
hub / github.com/pydantic/pydantic / _mapping_schema

Method _mapping_schema

pydantic/_internal/_generate_schema.py:598–642  ·  view source on GitHub ↗
(self, tp: Any, keys_type: Any, values_type: Any)

Source from the content-addressed store, hash-verified

596 )
597
598 def _mapping_schema(self, tp: Any, keys_type: Any, values_type: Any) -> CoreSchema:
599 from ._validators import MAPPING_ORIGIN_MAP, defaultdict_validator, get_defaultdict_default_default_factory
600
601 mapped_origin = MAPPING_ORIGIN_MAP[tp]
602 keys_schema = self.generate_schema(keys_type)
603 with warnings.catch_warnings():
604 # We kind of abused `Field()` default factories to be able to specify
605 # the `defaultdict`'s `default_factory`. As a consequence, we get warnings
606 # as normally `FieldInfo.default_factory` is unsupported in the context where
607 # `Field()` is used and our only solution is to ignore them (note that this might
608 # wrongfully ignore valid warnings, e.g. if the `value_type` is a PEP 695 type alias
609 # with unsupported metadata).
610 warnings.simplefilter('ignore', category=UnsupportedFieldAttributeWarning)
611 values_schema = self.generate_schema(values_type)
612 dict_schema = core_schema.dict_schema(keys_schema, values_schema, strict=False)
613
614 if mapped_origin is dict:
615 schema = dict_schema
616 else:
617 check_instance = core_schema.json_or_python_schema(
618 json_schema=dict_schema,
619 python_schema=core_schema.is_instance_schema(mapped_origin),
620 )
621
622 if tp is collections.defaultdict:
623 default_default_factory = get_defaultdict_default_default_factory(values_type)
624 coerce_instance_wrap = partial(
625 core_schema.no_info_wrap_validator_function,
626 partial(defaultdict_validator, default_default_factory=default_default_factory),
627 )
628 else:
629 coerce_instance_wrap = partial(core_schema.no_info_after_validator_function, mapped_origin)
630
631 lax_schema = coerce_instance_wrap(dict_schema)
632 strict_schema = core_schema.chain_schema([check_instance, lax_schema])
633
634 schema = core_schema.lax_or_strict_schema(
635 lax_schema=lax_schema,
636 strict_schema=strict_schema,
637 serialization=core_schema.wrap_serializer_function_ser_schema(
638 lambda v, h: h(v), schema=dict_schema, info_arg=False
639 ),
640 )
641
642 return schema
643
644 def _fraction_schema(self) -> CoreSchema:
645 """Support for [`fractions.Fraction`][fractions.Fraction]."""

Callers 2

match_typeMethod · 0.95
_match_generic_typeMethod · 0.95

Calls 7

generate_schemaMethod · 0.95
dict_schemaMethod · 0.80
json_or_python_schemaMethod · 0.80
is_instance_schemaMethod · 0.80
chain_schemaMethod · 0.80
lax_or_strict_schemaMethod · 0.80

Tested by

no test coverage detected