BaseModel
Pydantic models are simply classes which inherit from BaseModel and define fields as annotated attributes.
BaseModel
Section titled “BaseModel”A base class for creating Pydantic models.
Attributes
Section titled “Attributes”__class_vars__
Section titled “__class_vars__”The names of the class variables defined on the model.
__private_attributes__
Section titled “__private_attributes__”Metadata about the private attributes of the model.
Type: Dict[str, ModelPrivateAttr]
__signature__
Section titled “__signature__”The synthesized __init__ Signature of the model.
Type: Signature
__pydantic_complete__
Section titled “__pydantic_complete__”Whether model building is completed, or if there are still undefined fields.
Type: bool
__pydantic_core_schema__
Section titled “__pydantic_core_schema__”The core schema of the model.
Type: CoreSchema
__pydantic_custom_init__
Section titled “__pydantic_custom_init__”Whether the model has a custom __init__ function.
Type: bool
__pydantic_decorators__
Section titled “__pydantic_decorators__”Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.
Type: _decorators.DecoratorInfos
__pydantic_generic_metadata__
Section titled “__pydantic_generic_metadata__”A dictionary containing metadata about generic Pydantic models. The origin and args items map to the __origin__ and __args__ attributes of generic aliases, and the parameter item maps to the __parameter__ attribute of generic classes.
Type: _generics.PydanticGenericMetadata
__pydantic_parent_namespace__
Section titled “__pydantic_parent_namespace__”Parent namespace of the model, used for automatic rebuilding of models.
__pydantic_post_init__
Section titled “__pydantic_post_init__”The name of the post-init method for the model, if defined.
Type: None | Literal[‘model_post_init’]
__pydantic_root_model__
Section titled “__pydantic_root_model__”Whether the model is a RootModel.
Type: bool
__pydantic_serializer__
Section titled “__pydantic_serializer__”The pydantic-core SchemaSerializer used to dump instances of the model.
Type: SchemaSerializer
__pydantic_validator__
Section titled “__pydantic_validator__”The pydantic-core SchemaValidator used to validate instances of the model.
Type: SchemaValidator | PluggableSchemaValidator
__pydantic_fields__
Section titled “__pydantic_fields__”A dictionary of field names and their corresponding FieldInfo objects.
__pydantic_computed_fields__
Section titled “__pydantic_computed_fields__”A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
Type: Dict[str, ComputedFieldInfo]
__pydantic_extra__
Section titled “__pydantic_extra__”A dictionary containing extra values, if extra is set to 'allow'.
__pydantic_fields_set__
Section titled “__pydantic_fields_set__”The names of fields explicitly set during instantiation.
__pydantic_private__
Section titled “__pydantic_private__”Values of private attributes set on the model instance.
model_config
Section titled “model_config”Configuration for the model, should be a dictionary conforming to ConfigDict.
Type: ConfigDict Default: ConfigDict()
model_extra
Section titled “model_extra”Get extra fields set during validation.
model_fields_set
Section titled “model_fields_set”Returns the set of fields that have been explicitly set on this model instance.
Methods
Section titled “Methods”__init__
Section titled “__init__”def __init__(**data: Any) -> NoneRaises ValidationError if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Returns
Section titled “Returns”model_fields
Section titled “model_fields”@classmethod
def model_fields(cls) -> dict[str, FieldInfo]A mapping of field names to their respective FieldInfo instances.
Returns
Section titled “Returns”model_computed_fields
Section titled “model_computed_fields”@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]A mapping of computed field names to their respective ComputedFieldInfo instances.
Returns
Section titled “Returns”model_construct
Section titled “model_construct”@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> SelfCreates 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.
Returns
Section titled “Returns”Self — A new instance of the Model class with validated data.
Parameters
Section titled “Parameters”_fields_set : set[str] | None Default: None
A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the model_fields_set attribute. Otherwise, the field names from the values argument will be used.
values : Any Default: {}
Trusted or pre-validated data dictionary.
model_copy
Section titled “model_copy”def model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) -> SelfReturns a copy of the model.
Returns
Section titled “Returns”Self — New model instance.
Parameters
Section titled “Parameters”update : Mapping[str, Any] | None Default: None
Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep : bool Default: False
Set to True to make a deep copy of the model.
model_dump
Section titled “model_dump”def model_dump(
*,
mode: Literal['json', 'python'] | str = 'python',
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
polymorphic_serialization: bool | None = None,
) -> dict[str, Any]Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Returns
Section titled “Returns”dict[str, Any] — A dictionary representation of the model.
Parameters
Section titled “Parameters”mode : Literal[‘json’, ‘python’] | str Default: 'python'
The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include : IncEx | None Default: None
A set of fields to include in the output.
exclude : IncEx | None Default: None
A set of fields to exclude from the output.
context : Any | None Default: None
Additional context to pass to the serializer.
by_alias : bool | None Default: None
Whether to use the field’s alias in the dictionary key if defined.
exclude_unset : bool Default: False
Whether to exclude fields that have not been explicitly set.
exclude_defaults : bool Default: False
Whether to exclude fields that are set to their default value.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
exclude_computed_fields : bool Default: False
Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip : bool Default: False
If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings : bool | Literal[‘none’, ‘warn’, ‘error’] Default: True
How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors, “error” raises a PydanticSerializationError.
fallback : Callable[[Any], Any] | None Default: None
A function to call when an unknown value is encountered. If not provided, a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization : bool | None Default: None
Whether to use model and dataclass polymorphic serialization for this call.
model_dump_json
Section titled “model_dump_json”def model_dump_json(
*,
indent: int | None = None,
ensure_ascii: bool = False,
include: IncEx | None = None,
exclude: IncEx | None = None,
context: Any | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
polymorphic_serialization: bool | None = None,
) -> strGenerates a JSON representation of the model using Pydantic’s to_json method.
Returns
Section titled “Returns”str — A JSON string representation of the model.
Parameters
Section titled “Parameters”indent : int | None Default: None
Indentation to use in the JSON output. If None is passed, the output will be compact.
ensure_ascii : bool Default: False
If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.
include : IncEx | None Default: None
Field(s) to include in the JSON output.
exclude : IncEx | None Default: None
Field(s) to exclude from the JSON output.
context : Any | None Default: None
Additional context to pass to the serializer.
by_alias : bool | None Default: None
Whether to serialize using field aliases.
exclude_unset : bool Default: False
Whether to exclude fields that have not been explicitly set.
exclude_defaults : bool Default: False
Whether to exclude fields that are set to their default value.
exclude_none : bool Default: False
Whether to exclude fields that have a value of None.
exclude_computed_fields : bool Default: False
Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip : bool Default: False
If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings : bool | Literal[‘none’, ‘warn’, ‘error’] Default: True
How to handle serialization errors. False/“none” ignores them, True/“warn” logs errors, “error” raises a PydanticSerializationError.
fallback : Callable[[Any], Any] | None Default: None
A function to call when an unknown value is encountered. If not provided, a PydanticSerializationError error is raised.
serialize_as_any : bool Default: False
Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization : bool | None Default: None
Whether to use model and dataclass polymorphic serialization for this call.
model_json_schema
Section titled “model_json_schema”@classmethod
def model_json_schema(
cls,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
mode: JsonSchemaMode = 'validation',
*,
union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]Generates a JSON schema for a model class.
Returns
Section titled “Returns”dict[str, Any] — The JSON schema for the given model class.
Parameters
Section titled “Parameters”by_alias : bool Default: True
Whether to use attribute aliases or not.
ref_template : str Default: DEFAULT_REF_TEMPLATE
The reference template.
union_format : Literal[‘any_of’, ‘primitive_type_array’] Default: 'any_of'
The format to use when combining schemas from unions together. Can be one of:
'any_of': Use theanyOfkeyword to combine schemas (the default).'primitive_type_array': Use thetypekeyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string,boolean,null,integerornumber) or contains constraints/metadata, falls back toany_of.
schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema
To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode : JsonSchemaMode Default: 'validation'
The mode in which to generate the schema.
model_parametrized_name
Section titled “model_parametrized_name”@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> strCompute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
Returns
Section titled “Returns”str — String representing the new class where params are passed to cls as type variables.
Parameters
Section titled “Parameters”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.
Raises
Section titled “Raises”TypeError— Raised when trying to generate concrete names for non-generic models.
model_post_init
Section titled “model_post_init”def model_post_init(context: Any, /) -> NoneOverride 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.
Returns
Section titled “Returns”model_rebuild
Section titled “model_rebuild”@classmethod
def model_rebuild(
cls,
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: MappingNamespace | None = None,
) -> bool | NoneTry 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.
Returns
Section titled “Returns”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.
Parameters
Section titled “Parameters”force : bool Default: False
Whether to force the rebuilding of the model schema, defaults to False.
raise_errors : bool Default: True
Whether to raise errors, defaults to True.
_parent_namespace_depth : int Default: 2
The depth level of the parent namespace, defaults to 2.
_types_namespace : MappingNamespace | None Default: None
The types namespace, defaults to None.
model_validate
Section titled “model_validate”@classmethod
def model_validate(
cls,
obj: Any,
*,
strict: bool | None = None,
extra: ExtraValues | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> SelfValidate a pydantic model instance.
Returns
Section titled “Returns”Self — The validated model instance.
Parameters
Section titled “Parameters”obj : Any
The object to validate.
strict : bool | None Default: None
Whether to enforce types strictly.
extra : ExtraValues | None Default: None
Whether to ignore, allow, or forbid extra data during model validation. See the extra configuration value for details.
from_attributes : bool | None Default: None
Whether to extract data from object attributes.
context : Any | None Default: None
Additional context to pass to the validator.
by_alias : bool | None Default: None
Whether to use the field’s alias when validating against the provided input data.
by_name : bool | None Default: None
Whether to use the field’s name when validating against the provided input data.
Raises
Section titled “Raises”ValidationError— If the object could not be validated.
model_validate_json
Section titled “model_validate_json”@classmethod
def model_validate_json(
cls,
json_data: str | bytes | bytearray,
*,
strict: bool | None = None,
extra: ExtraValues | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> SelfValidate the given JSON data against the Pydantic model.
A ValidationError raised here names the failing fields, but not the JSON document they came from. Recording validations with Logfire keeps the offending input alongside the error — see Troubleshooting validation errors.
Returns
Section titled “Returns”Self — The validated Pydantic model.
Parameters
Section titled “Parameters”json_data : str | bytes | bytearray
The JSON data to validate.
strict : bool | None Default: None
Whether to enforce types strictly.
extra : ExtraValues | None Default: None
Whether to ignore, allow, or forbid extra data during model validation. See the extra configuration value for details.
context : Any | None Default: None
Extra variables to pass to the validator.
by_alias : bool | None Default: None
Whether to use the field’s alias when validating against the provided input data.
by_name : bool | None Default: None
Whether to use the field’s name when validating against the provided input data.
Raises
Section titled “Raises”ValidationError— Ifjson_datais not a JSON string or the object could not be validated.
model_validate_strings
Section titled “model_validate_strings”@classmethod
def model_validate_strings(
cls,
obj: Any,
*,
strict: bool | None = None,
extra: ExtraValues | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> SelfValidate the given object with string data against the Pydantic model.
Returns
Section titled “Returns”Self — The validated Pydantic model.
Parameters
Section titled “Parameters”obj : Any
The object containing string data to validate.
strict : bool | None Default: None
Whether to enforce types strictly.
extra : ExtraValues | None Default: None
Whether to ignore, allow, or forbid extra data during model validation. See the extra configuration value for details.
context : Any | None Default: None
Extra variables to pass to the validator.
by_alias : bool | None Default: None
Whether to use the field’s alias when validating against the provided input data.
by_name : bool | None Default: None
Whether to use the field’s name when validating against the provided input data.
create_model
Section titled “create_model”def create_model(
model_name: str,
/,
*,
__config__: ConfigDict | None = None,
__doc__: str | None = None,
__base__: None = None,
__module__: str = __name__,
__validators__: dict[str, Callable[..., Any]] | None = None,
__cls_kwargs__: dict[str, Any] | None = None,
__qualname__: str | None = None,
**field_definitions: Any | tuple[Any, Any],
) -> type[BaseModel]
def create_model(
model_name: str,
/,
*,
__config__: ConfigDict | None = None,
__doc__: str | None = None,
__base__: type[ModelT] | tuple[type[ModelT], ...],
__module__: str = __name__,
__validators__: dict[str, Callable[..., Any]] | None = None,
__cls_kwargs__: dict[str, Any] | None = None,
__qualname__: str | None = None,
**field_definitions: Any | tuple[Any, Any],
) -> type[ModelT]Dynamically creates and returns a new Pydantic model, in other words, create_model dynamically creates a subclass of BaseModel.
Returns
Section titled “Returns”Parameters
Section titled “Parameters”model_name : str
The name of the newly created model.
__config__ : ConfigDict | None Default: None
The configuration of the new model.
__doc__ : str | None Default: None
The docstring of the new model.
__base__ : type[ModelT] | tuple[type[ModelT], …] | None Default: None
The base class or classes for the new model.
__module__ : str | None Default: None
The name of the module that the model belongs to; if None, the value is taken from sys._getframe(1)
__validators__ : dict[str, Callable[…, Any]] | None Default: None
A dictionary of methods that validate fields. The keys are the names of the validation methods to be added to the model, and the values are the validation methods themselves. You can read more about functional validators here.
__cls_kwargs__ : dict[str, Any] | None Default: None
A dictionary of keyword arguments for class creation, such as metaclass.
__qualname__ : str | None Default: None
The qualified name of the newly created model.
**field_definitions : Any | tuple[Any, Any] Default: {}
Field definitions of the new model. Either:
- a single element, representing the type annotation of the field.
- a two-tuple, the first element being the type and the second element the assigned value (either a default or the
Field()function).
Raises
Section titled “Raises”PydanticUserError— If__base__and__config__are both passed.
Was this page helpful?