RootModel
RootModel class and type definitions.
Bases: PydanticErrorMixin, TypeError
An error raised due to incorrect use of Pydantic.
Usage docs: https://docs.pydantic.dev/2.5/concepts/models/
A base class for creating Pydantic models.
Configuration for the model, should be a dictionary conforming to ConfigDict.
Type: ConfigDict Default: ConfigDict()
Metadata about the fields defined on the model,
mapping of field names to FieldInfo.
This replaces Model.__fields__ from Pydantic V1.
Type: dict[str, FieldInfo]
Get the computed fields of this model instance.
Type: dict[str, ComputedFieldInfo]
Get extra fields set during validation.
Type: dict[str, Any] | None
Returns the set of fields that have been explicitly set on this model instance.
Type: set[str]
def __init__(__pydantic_self__, data: Any = {}) -> None
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be
validated to form a valid model.
__init__ uses __pydantic_self__ instead of the more common self for the first arg to
allow self as a field name.
None
@classmethod
def model_construct(
cls: type[Model],
_fields_set: set[str] | None = None,
values: Any = {},
) -> Model
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = 'allow' was set since it adds all passed values
Model — A new instance of the Model class with validated data.
The set of field names accepted for the Model instance.
Trusted or pre-validated data dictionary.
def model_copy(update: dict[str, Any] | None = None, deep: bool = False) -> Model
Usage docs: https://docs.pydantic.dev/2.5/concepts/serialization/#model_copy
Returns a copy of the model.
Model — New model instance.
Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
Set to True to make a deep copy of the model.
def model_dump(
mode: Literal['json', 'python'] | str = 'python',
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> dict[str, Any]
Usage docs: https://docs.pydantic.dev/2.5/concepts/serialization/#modelmodel_dump
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
dict[str, Any] — A dictionary representation of the model.
The mode in which to_python should run.
If mode is ‘json’, the dictionary will only contain JSON serializable types.
If mode is ‘python’, the dictionary may contain any Python objects.
A list of fields to include in the output.
A list of fields to exclude from the output.
Whether to use the field’s alias in the dictionary key if defined.
Whether to exclude fields that have not been explicitly set.
Whether to exclude fields that are set to their default value from the output.
Whether to exclude fields that have a value of None from the output.
Whether to enable serialization and deserialization round-trip support.
Whether to log warnings when invalid fields are encountered.
def model_dump_json(
indent: int | None = None,
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> str
Usage docs: https://docs.pydantic.dev/2.5/concepts/serialization/#modelmodel_dump_json
Generates a JSON representation of the model using Pydantic’s to_json method.
str — A JSON string representation of the model.
Indentation to use in the JSON output. If None is passed, the output will be compact.
Field(s) to include in the JSON output. Can take either a string or set of strings.
Field(s) to exclude from the JSON output. Can take either a string or set of strings.
Whether to serialize using field aliases.
Whether to exclude fields that have not been explicitly set.
Whether to exclude fields that have the default value.
Whether to exclude fields that have a value of None.
Whether to use serialization/deserialization between JSON and class instance.
Whether to show any warnings that occurred during serialization.
@classmethod
def model_json_schema(
cls,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]
Generates a JSON schema for a model class.
dict[str, Any] — The JSON schema for the given model class.
Whether to use attribute aliases or not.
The reference template.
To override the logic used to generate the JSON schema, as a subclass of
GenerateJsonSchema with your desired modifications
The mode in which to generate the schema.
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
str — String representing the new class where params are passed to cls as type variables.
Tuple of types of the class. Given a generic class
Model with 2 type variables and a concrete model Model[str, int],
the value (str, int) would be passed to params.
TypeError— Raised when trying to generate concrete names for non-generic models.
def model_post_init(__context: Any) -> None
Override this method to perform additional initialization after __init__ and model_construct.
This is useful if you want to do some validation that requires the entire model to be initialized.
None
@classmethod
def model_rebuild(
cls,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: dict[str, Any] | None = None,
) -> bool | None
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
bool | None — Returns None if the schema is already “complete” and rebuilding was not required.
bool | None — If rebuilding was required, returns True if rebuilding was successful, otherwise False.
Whether to force the rebuilding of the model schema, defaults to False.
Whether to raise errors, defaults to True.
The depth level of the parent namespace, defaults to 2.
The types namespace, defaults to None.
@classmethod
def model_validate(
cls: type[Model],
obj: Any,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Model
Validate a pydantic model instance.
Model — The validated model instance.
The object to validate.
Whether to raise an exception on invalid fields.
Whether to extract data from object attributes.
Additional context to pass to the validator.
ValidationError— If the object could not be validated.
@classmethod
def model_validate_json(
cls: type[Model],
json_data: str | bytes | bytearray,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Model
Usage docs: https://docs.pydantic.dev/2.5/concepts/json/#json-parsing
Validate the given JSON data against the Pydantic model.
Model — The validated Pydantic model.
The JSON data to validate.
Whether to enforce types strictly.
Extra variables to pass to the validator.
ValueError— Ifjson_datais not a JSON string.
@classmethod
def model_validate_strings(
cls: type[Model],
obj: Any,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Model
Validate the given object contains string data against the Pydantic model.
Model — The validated Pydantic model.
The object contains string data to validate.
Whether to enforce types strictly.
Extra variables to pass to the validator.
@classmethod
def __get_pydantic_core_schema__(
cls,
__source: type[BaseModel],
__handler: GetCoreSchemaHandler,
) -> CoreSchema
Hook into generating the model’s CoreSchema.
CoreSchema — A pydantic-core CoreSchema.
The class we are generating a schema for.
This will generally be the same as the cls argument if this is a classmethod.
Call into Pydantic’s internal JSON schema generation. A callable that calls into Pydantic’s internal CoreSchema generation logic.
@classmethod
def __get_pydantic_json_schema__(
cls,
__core_schema: CoreSchema,
__handler: GetJsonSchemaHandler,
) -> JsonSchemaValue
Hook into generating the model’s JSON schema.
JsonSchemaValue — A JSON schema, as a Python object.
A pydantic-core CoreSchema.
You can ignore this argument and call the handler with a new CoreSchema,
wrap this CoreSchema (\{'type': 'nullable', 'schema': current_schema\}),
or just call the handler with the original schema.
Call into Pydantic’s internal JSON schema generation.
This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema
generation fails.
Since this gets called by BaseModel.model_json_schema you can override the
schema_generator argument to that function to change JSON schema generation globally
for a type.
@classmethod
def __pydantic_init_subclass__(cls, kwargs: Any = {}) -> None
This is intended to behave just like __init_subclass__, but is called by ModelMetaclass
only after the class is actually fully initialized. In particular, attributes like model_fields will
be present when this is called.
This is necessary because __init_subclass__ will always be called by type.__new__,
and it would require a prohibitively large refactor to the ModelMetaclass to ensure that
type.__new__ was called in such a manner that the class would already be sufficiently initialized.
This will receive the same kwargs that would be passed to the standard __init_subclass__, namely,
any kwargs passed to the class definition that aren’t used internally by pydantic.
None
Any keyword arguments passed to the class definition that aren’t used internally by pydantic.
def __copy__() -> Model
Returns a shallow copy of the model.
Model
def __deepcopy__(memo: dict[int, Any] | None = None) -> Model
Returns a deep copy of the model.
Model
def __init_subclass__(cls, kwargs: Unpack[ConfigDict] = {})
This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.
from pydantic import BaseModel
class MyModel(BaseModel, extra='allow'):
...
However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any
of the config arguments, and will only receive any keyword arguments passed during class initialization
that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)
Keyword arguments passed to the class definition, which set model_config
def __iter__() -> TupleGenerator
So dict(model) works.
TupleGenerator
def dict(
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
) -> typing.Dict[str, Any]
typing.Dict[str, Any]
def json(
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
encoder: typing.Callable[[Any], Any] | None = PydanticUndefined,
models_as_dict: bool = PydanticUndefined,
dumps_kwargs: Any = {},
) -> str
str
@classmethod
def parse_obj(cls: type[Model], obj: Any) -> Model
Model
@classmethod
def parse_raw(
cls: type[Model],
b: str | bytes,
content_type: str | None = None,
encoding: str = 'utf8',
proto: DeprecatedParseProtocol | None = None,
allow_pickle: bool = False,
) -> Model
Model
@classmethod
def parse_file(
cls: type[Model],
path: str | Path,
content_type: str | None = None,
encoding: str = 'utf8',
proto: DeprecatedParseProtocol | None = None,
allow_pickle: bool = False,
) -> Model
Model
@classmethod
def from_orm(cls: type[Model], obj: Any) -> Model
Model
@classmethod
def construct(
cls: type[Model],
_fields_set: set[str] | None = None,
values: Any = {},
) -> Model
Model
def copy(
include: AbstractSetIntStr | MappingIntStrAny | None = None,
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
update: typing.Dict[str, Any] | None = None,
deep: bool = False,
) -> Model
Returns a copy of the model.
If you need include or exclude, use:
data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)
Model — A copy of the model with included, excluded and updated fields as specified.
Optional set or mapping specifying which fields to include in the copied model.
Optional set or mapping specifying which fields to exclude in the copied model.
Optional dictionary of field-value pairs to override field values in the copied model.
If True, the values of fields that are Pydantic models will be deep copied.
@classmethod
def schema(
cls,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
) -> typing.Dict[str, Any]
typing.Dict[str, Any]
@classmethod
def schema_json(
cls,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
dumps_kwargs: Any = {},
) -> str
str
@classmethod
def validate(cls: type[Model], value: Any) -> Model
Model
@classmethod
def update_forward_refs(cls, localns: Any = {}) -> None
None
Bases: BaseModel, Generic[RootModelRootType]
Usage docs: https://docs.pydantic.dev/2.5/concepts/models/#rootmodel-and-custom-root-types
A Pydantic BaseModel for the root object of the model.
Type: RootModelRootType
@classmethod
def model_construct(
cls: type[Model],
root: RootModelRootType,
_fields_set: set[str] | None = None,
) -> Model
Create a new model using the provided root object and update fields set.
Model — The new model.
The root object of the model.
The set of fields to be updated.
NotImplemented— If the model is not a subclass ofRootModel.
def __copy__() -> Model
Returns a shallow copy of the model.
Model
def __deepcopy__(memo: dict[int, Any] | None = None) -> Model
Returns a deep copy of the model.
Model
def model_dump(
mode: Literal['json', 'python'] | str = 'python',
include: Any = None,
exclude: Any = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> RootModelRootType
This method is included just to get a more accurate return type for type checkers.
It is included in this if TYPE_CHECKING: block since no override is actually necessary.
See the documentation of BaseModel.model_dump for more details about the arguments.
RootModelRootType
Default: typing.TypeVar('Model', bound='BaseModel')
Default: typing.TypeVar('RootModelRootType')