MCPcopy
hub / github.com/pydantic/pydantic / add_model_construct_method

Method add_model_construct_method

pydantic/mypy.py:941–979  ·  view source on GitHub ↗

Adds a fully typed `model_construct` classmethod to the class. Similar to the fields-aware __init__ method, but always uses the field names (not aliases), and does not treat settings fields as optional.

(
        self,
        fields: list[PydanticModelField],
        config: ModelConfigData,
        is_settings: bool,
        is_root_model: bool,
    )

Source from the content-addressed store, hash-verified

939 add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType())
940
941 def add_model_construct_method(
942 self,
943 fields: list[PydanticModelField],
944 config: ModelConfigData,
945 is_settings: bool,
946 is_root_model: bool,
947 ) -> None:
948 """Adds a fully typed `model_construct` classmethod to the class.
949
950 Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
951 and does not treat settings fields as optional.
952 """
953 set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')])
954 optional_set_str = UnionType([set_str, NoneType()])
955 fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
956 with state.strict_optional_set(self._api.options.strict_optional):
957 args = self.get_field_arguments(
958 fields,
959 typed=True,
960 model_strict=bool(config.strict),
961 requires_dynamic_aliases=False,
962 use_alias=False,
963 is_settings=is_settings,
964 is_root_model=is_root_model,
965 )
966 if not self.should_init_forbid_extra(fields, config):
967 var = Var('kwargs')
968 args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
969
970 args = args + [fields_set_argument] if is_root_model else [fields_set_argument] + args
971
972 add_method(
973 self._api,
974 self._cls,
975 'model_construct',
976 args=args,
977 return_type=fill_typevars(self._cls.info),
978 is_classmethod=True,
979 )
980
981 def set_frozen(self, fields: list[PydanticModelField], api: SemanticAnalyzerPluginInterface, frozen: bool) -> None:
982 """Marks all fields as properties so that attempts to set them trigger mypy errors.

Callers 1

transformMethod · 0.95

Calls 3

get_field_argumentsMethod · 0.95
add_methodFunction · 0.70

Tested by

no test coverage detected