TypeAdapter
A class representing the type adapter.
Bases: PydanticErrorMixin, TypeError
An error raised due to incorrect use of Pydantic.
Usage docs: https://docs.pydantic.dev/2.2/usage/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 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.2/usage/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.2/usage/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 are unset or None from the output.
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.2/usage/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
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 __get_pydantic_core_schema__(
cls,
__source: type[BaseModel],
__handler: _annotated_handlers.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: _annotated_handlers.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: _deprecated_parse.Protocol | 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: _deprecated_parse.Protocol | 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: TypedDict
Usage docs: https://docs.pydantic.dev/2.2/usage/model_config/
A TypedDict for configuring Pydantic behaviour.
The title for the generated JSON schema, defaults to the model’s name
Type: str | None
Whether to convert all characters to lowercase for str types. Defaults to False.
Type: bool
Whether to convert all characters to uppercase for str types. Defaults to False.
Type: bool
Whether to strip leading and trailing whitespace for str types.
Type: bool
The minimum length for str types. Defaults to None.
Type: int
The maximum length for str types. Defaults to None.
Type: int | None
Whether to ignore, allow, or forbid extra attributes during model initialization.
The value must be a ExtraValues string. Defaults to 'ignore'.
See Extra Attributes for details.
Type: ExtraValues | None
Whether or not models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates
a __hash__() method for the model. This makes instances of the model potentially hashable if all the
attributes are hashable. Defaults to False.
Type: bool
Whether an aliased field may be populated by its name as given by the model
attribute, as well as the alias. Defaults to False.
Type: bool
Whether to populate models with the value property of enums, rather than the raw enum.
This may be useful if you want to serialize model.model_dump() later. Defaults to False.
Type: bool
Type: bool
Type: bool
Whether to build models and look up discriminators of tagged unions using python object attributes.
Type: bool
Whether to use the alias for error locs rather than the field’s name. Defaults to True.
Type: bool
A callable that takes a field name and returns an alias for it.
See Alias Generator for details.
Type: Callable[[str], str] | None
A tuple of types that may occur as values of class attributes without annotations. This is
typically used for custom descriptors (classes that behave like property). If an attribute is set on a
class without an annotation and has a type that is not in this tuple (or otherwise recognized by
pydantic), an error will be raised. Defaults to ().
Type: tuple[type, ...]
Whether to allow infinity (+inf an -inf) and NaN values to float fields. Defaults to True.
Type: bool
A dict or callable to provide extra JSON schema properties. Defaults to None.
Type: dict[str, object] | JsonSchemaExtraCallable | None
A dict of custom JSON encoders for specific types. Defaults to None.
Type: dict[type[object], JsonEncoder] | None
(new in V2) If True, strict validation is applied to all fields on the model.
See Strict Mode for details.
Type: bool
When and how to revalidate models and dataclasses during validation. Accepts the string
values of 'never', 'always' and 'subclass-instances'. Defaults to 'never'.
'never'will not revalidate models and dataclasses during validation'always'will revalidate models and dataclasses during validation'subclass-instances'will revalidate models and dataclasses during validation if the instance is a subclass of the model or dataclass
See Revalidate Instances for details.
Type: Literal['always', 'never', 'subclass-instances']
The format of JSON serialized timedeltas. Accepts the string values of 'iso8601' and
'float'. Defaults to 'iso8601'.
'iso8601'will serialize timedeltas to ISO 8601 durations.'float'will serialize timedeltas to the total number of seconds.
Type: Literal['iso8601', 'float']
The encoding of JSON serialized bytes. Accepts the string values of 'utf8' and 'base64'.
Defaults to 'utf8'.
'utf8'will serialize bytes to UTF-8 strings.'base64'will serialize bytes to URL safe base64 strings.
Type: Literal['utf8', 'base64']
Whether to validate default values during validation. Defaults to False.
Type: bool
whether to validate the return value from call validators.
Type: bool
A tuple of strings that prevent model to have field which conflict with them.
Defaults to ('model_', )).
See Protected Namespaces for details.
Type: tuple[str, ...]
Whether to hide inputs when printing errors. Defaults to False.
See Hide Input in Errors.
Type: bool
Whether to defer model validator and serializer construction until the first model validation.
This can be useful to avoid the overhead of building models which are only
used nested within other models, or when you want to manually define type namespace via
Model.model_rebuild(_types_namespace=...). Defaults to False.
Type: bool
A custom core schema generator class to use when generating JSON schemas. Useful if you want to change the way types are validated across an entire model/schema.
The GenerateSchema interface is subject to change, currently only the string_schema method is public.
See #6737 for details.
Defaults to None.
Type: type[_GenerateSchema] | None
A class for generating JSON schemas.
This class generates JSON schemas based on configured parameters. The default schema dialect
is https://json-schema.org/draft/2020-12/schema.
The class uses by_alias to configure how fields with
multiple names are handled and ref_template to format reference names.
Whether or not to include field names.
The format string to use when generating reference names.
Default: 'https://json-schema.org/draft/2020-12/schema'
Type: set[JsonSchemaWarningKind] Default: \{'skipped-choice'\}
Default: by_alias
Default: ref_template
Type: dict[CoreModeRef, JsonRef] Default: \{\}
Type: dict[CoreModeRef, DefsRef] Default: \{\}
Type: dict[DefsRef, CoreModeRef] Default: \{\}
Type: dict[JsonRef, DefsRef] Default: \{\}
Type: dict[DefsRef, JsonSchemaValue] Default: \{\}
Type: JsonSchemaMode Default: 'validation'
def build_schema_type_to_method(
) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]
Builds a dictionary mapping fields to methods for generating JSON schemas.
dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] — A dictionary containing the mapping of CoreSchemaOrFieldType to a handler method.
TypeError— If no method has been defined for generating a JSON schema for a given pydantic core schema type.
def generate_definitions(
inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]],
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]
Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a mapping that links the input keys to the definition references.
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]] — A tuple where:
- The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
- The second element is a dictionary whose keys are definition references for the JSON schemas from the first returned element, and whose values are the actual JSON schema definitions.
A sequence of tuples, where:
- The first element is a JSON schema key type.
- The second element is the JSON mode: either ‘validation’ or ‘serialization’.
- The third element is a core schema.
PydanticUserError— Raised if the JSON schema generator has already been used to generate a JSON schema.
def generate(schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue
Generates a JSON schema for a specified schema in a specified mode.
JsonSchemaValue — A JSON schema representing the specified schema.
A Pydantic model.
The mode in which to generate the schema. Defaults to ‘validation’.
PydanticUserError— If the JSON schema generator has already been used to generate a JSON schema.
def generate_inner(schema: CoreSchemaOrField) -> JsonSchemaValue
Generates a JSON schema for a given core schema.
JsonSchemaValue — The generated JSON schema.
The given core schema.
def any_schema(schema: core_schema.AnySchema) -> JsonSchemaValue
Generates a JSON schema that matches any value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def none_schema(schema: core_schema.NoneSchema) -> JsonSchemaValue
Generates a JSON schema that matches a None value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def bool_schema(schema: core_schema.BoolSchema) -> JsonSchemaValue
Generates a JSON schema that matches a bool value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def int_schema(schema: core_schema.IntSchema) -> JsonSchemaValue
Generates a JSON schema that matches an Int value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def float_schema(schema: core_schema.FloatSchema) -> JsonSchemaValue
Generates a JSON schema that matches a float value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def decimal_schema(schema: core_schema.DecimalSchema) -> JsonSchemaValue
Generates a JSON schema that matches a decimal value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def str_schema(schema: core_schema.StringSchema) -> JsonSchemaValue
Generates a JSON schema that matches a string value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def bytes_schema(schema: core_schema.BytesSchema) -> JsonSchemaValue
Generates a JSON schema that matches a bytes value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def date_schema(schema: core_schema.DateSchema) -> JsonSchemaValue
Generates a JSON schema that matches a date value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def time_schema(schema: core_schema.TimeSchema) -> JsonSchemaValue
Generates a JSON schema that matches a time value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def datetime_schema(schema: core_schema.DatetimeSchema) -> JsonSchemaValue
Generates a JSON schema that matches a datetime value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def timedelta_schema(schema: core_schema.TimedeltaSchema) -> JsonSchemaValue
Generates a JSON schema that matches a timedelta value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def literal_schema(schema: core_schema.LiteralSchema) -> JsonSchemaValue
Generates a JSON schema that matches a literal value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def is_instance_schema(schema: core_schema.IsInstanceSchema) -> JsonSchemaValue
Generates a JSON schema that checks if a value is an instance of a class, equivalent to Python’s
isinstance method.
JsonSchemaValue — The generated JSON schema.
The core schema.
def is_subclass_schema(schema: core_schema.IsSubclassSchema) -> JsonSchemaValue
Generates a JSON schema that checks if a value is a subclass of a class, equivalent to Python’s issubclass
method.
JsonSchemaValue — The generated JSON schema.
The core schema.
def callable_schema(schema: core_schema.CallableSchema) -> JsonSchemaValue
Generates a JSON schema that matches a callable value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def list_schema(schema: core_schema.ListSchema) -> JsonSchemaValue
Returns a schema that matches a list schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def tuple_positional_schema(
schema: core_schema.TuplePositionalSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a positional tuple schema e.g. Tuple[int, str, bool].
JsonSchemaValue — The generated JSON schema.
The core schema.
def tuple_variable_schema(schema: core_schema.TupleVariableSchema) -> JsonSchemaValue
Generates a JSON schema that matches a variable tuple schema e.g. Tuple[int, ...].
JsonSchemaValue — The generated JSON schema.
The core schema.
def set_schema(schema: core_schema.SetSchema) -> JsonSchemaValue
Generates a JSON schema that matches a set schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def frozenset_schema(schema: core_schema.FrozenSetSchema) -> JsonSchemaValue
Generates a JSON schema that matches a frozenset schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def generator_schema(schema: core_schema.GeneratorSchema) -> JsonSchemaValue
Returns a JSON schema that represents the provided GeneratorSchema.
JsonSchemaValue — The generated JSON schema.
The schema.
def dict_schema(schema: core_schema.DictSchema) -> JsonSchemaValue
Generates a JSON schema that matches a dict schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def function_before_schema(
schema: core_schema.BeforeValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-before schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def function_after_schema(
schema: core_schema.AfterValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-after schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def function_plain_schema(
schema: core_schema.PlainValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-plain schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def function_wrap_schema(
schema: core_schema.WrapValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-wrap schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def default_schema(schema: core_schema.WithDefaultSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema with a default value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def nullable_schema(schema: core_schema.NullableSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows null values.
JsonSchemaValue — The generated JSON schema.
The core schema.
def union_schema(schema: core_schema.UnionSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
JsonSchemaValue — The generated JSON schema.
The core schema.
def tagged_union_schema(schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where the schemas are tagged with a discriminator field that indicates which schema should be used to validate the value.
JsonSchemaValue — The generated JSON schema.
The core schema.
def chain_schema(schema: core_schema.ChainSchema) -> JsonSchemaValue
Generates a JSON schema that matches a core_schema.ChainSchema.
When generating a schema for validation, we return the validation JSON schema for the first step in the chain. For serialization, we return the serialization JSON schema for the last step in the chain.
JsonSchemaValue — The generated JSON schema.
The core schema.
def lax_or_strict_schema(schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching either the lax schema or the strict schema.
JsonSchemaValue — The generated JSON schema.
The core schema.
def json_or_python_schema(schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the Python schema.
The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override this method.
JsonSchemaValue — The generated JSON schema.
The core schema.
def typed_dict_schema(schema: core_schema.TypedDictSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a typed dict.
JsonSchemaValue — The generated JSON schema.
The core schema.
def typed_dict_field_schema(schema: core_schema.TypedDictField) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a typed dict field.
JsonSchemaValue — The generated JSON schema.
The core schema.
def dataclass_field_schema(schema: core_schema.DataclassField) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass field.
JsonSchemaValue — The generated JSON schema.
The core schema.
def model_field_schema(schema: core_schema.ModelField) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model field.
JsonSchemaValue — The generated JSON schema.
The core schema.
def computed_field_schema(schema: core_schema.ComputedField) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a computed field.
JsonSchemaValue — The generated JSON schema.
The core schema.
def model_schema(schema: core_schema.ModelSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model.
JsonSchemaValue — The generated JSON schema.
The core schema.
def resolve_schema_to_update(json_schema: JsonSchemaValue) -> JsonSchemaValue
Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
JsonSchemaValue — The resolved schema.
The schema to resolve.
def model_fields_schema(schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model’s fields.
JsonSchemaValue — The generated JSON schema.
The core schema.
def field_is_present(field: CoreSchemaField) -> bool
Whether the field should be included in the generated JSON schema.
bool — True if the field should be included in the generated JSON schema, False otherwise.
The schema for the field itself.
def field_is_required(
field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
total: bool,
) -> bool
Whether the field should be marked as required in the generated JSON schema. (Note that this is irrelevant if the field is not present in the JSON schema.).
bool — True if the field should be marked as required in the generated JSON schema, False otherwise.
The schema for the field itself.
Only applies to TypedDictFields.
Indicates if the TypedDict this field belongs to is total, in which case any fields that don’t
explicitly specify required=False are required.
def dataclass_args_schema(schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass’s constructor arguments.
JsonSchemaValue — The generated JSON schema.
The core schema.
def dataclass_schema(schema: core_schema.DataclassSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass.
JsonSchemaValue — The generated JSON schema.
The core schema.
def arguments_schema(schema: core_schema.ArgumentsSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function’s arguments.
JsonSchemaValue — The generated JSON schema.
The core schema.
def kw_arguments_schema(
arguments: list[core_schema.ArgumentsParameter],
var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function’s keyword arguments.
JsonSchemaValue — The generated JSON schema.
The core schema.
def p_arguments_schema(
arguments: list[core_schema.ArgumentsParameter],
var_args_schema: CoreSchema | None,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function’s positional arguments.
JsonSchemaValue — The generated JSON schema.
The core schema.
def get_argument_name(argument: core_schema.ArgumentsParameter) -> str
Retrieves the name of an argument.
str — The name of the argument.
The core schema.
def call_schema(schema: core_schema.CallSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function call.
JsonSchemaValue — The generated JSON schema.
The core schema.
def custom_error_schema(schema: core_schema.CustomErrorSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a custom error.
JsonSchemaValue — The generated JSON schema.
The core schema.
def json_schema(schema: core_schema.JsonSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a JSON object.
JsonSchemaValue — The generated JSON schema.
The core schema.
def url_schema(schema: core_schema.UrlSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a URL.
JsonSchemaValue — The generated JSON schema.
The core schema.
def multi_host_url_schema(schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
JsonSchemaValue — The generated JSON schema.
The core schema.
def uuid_schema(schema: core_schema.UuidSchema) -> JsonSchemaValue
Generates a JSON schema that matches a UUID.
JsonSchemaValue — The generated JSON schema.
The core schema.
def definitions_schema(schema: core_schema.DefinitionsSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a JSON object with definitions.
JsonSchemaValue — The generated JSON schema.
The core schema.
def definition_ref_schema(
schema: core_schema.DefinitionReferenceSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that references a definition.
JsonSchemaValue — The generated JSON schema.
The core schema.
def ser_schema(
schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema,
) -> JsonSchemaValue | None
Generates a JSON schema that matches a schema that defines a serialized object.
JsonSchemaValue | None — The generated JSON schema.
The core schema.
def get_title_from_name(name: str) -> str
Retrieves a title from a name.
str — The title.
The name to retrieve a title from.
def field_title_should_be_set(schema: CoreSchemaOrField) -> bool
Returns true if a field with the given schema should have a title set based on the field name.
Intuitively, we want this to return true for schemas that wouldn’t otherwise provide their own title (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
bool — True if the field should have a title set, False otherwise.
The schema to check.
def normalize_name(name: str) -> str
Normalizes a name to be used as a key in a dictionary.
str — The normalized name.
The name to normalize.
def get_defs_ref(core_mode_ref: CoreModeRef) -> DefsRef
Override this method to change the way that definitions keys are generated from a core reference.
DefsRef — The definitions key.
The core reference.
def get_cache_defs_ref_schema(core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]
This method wraps the get_defs_ref method with some cache-lookup/population logic, and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
tuple[DefsRef, JsonSchemaValue] — A tuple of the definitions reference and the JSON schema that will refer to it.
The core reference to get the definitions reference for.
def handle_ref_overrides(json_schema: JsonSchemaValue) -> JsonSchemaValue
It is not valid for a schema with a top-level $ref to have sibling keys.
During our own schema generation, we treat sibling keys as overrides to the referenced schema, but this is not how the official JSON schema spec works.
Because of this, we first remove any sibling keys that are redundant with the referenced schema, then if any remain, we transform the schema from a top-level ‘$ref’ to use allOf to move the $ref out of the top level. (See bottom of https://swagger.io/docs/specification/using-ref/ for a reference about this behavior)
JsonSchemaValue
def get_schema_from_definitions(json_ref: JsonRef) -> JsonSchemaValue | None
JsonSchemaValue | None
def encode_default(dft: Any) -> Any
Encode a default value to a JSON-serializable value.
This is used to encode default values for fields in the generated JSON schema.
Any — The encoded default value.
The default value to encode.
def update_with_validations(
json_schema: JsonSchemaValue,
core_schema: CoreSchema,
mapping: dict[str, str],
) -> None
Update the json_schema with the corresponding validations specified in the core_schema, using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
None
The JSON schema to update.
The core schema to get the validations from.
A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
def get_flattened_anyof(schemas: list[JsonSchemaValue]) -> JsonSchemaValue
JsonSchemaValue
def get_json_ref_counts(json_schema: JsonSchemaValue) -> dict[JsonRef, int]
Get all values corresponding to the key ‘$ref’ anywhere in the json_schema.
dict[JsonRef, int]
def handle_invalid_for_json_schema(
schema: CoreSchemaOrField,
error_info: str,
) -> JsonSchemaValue
JsonSchemaValue
def emit_warning(kind: JsonSchemaWarningKind, detail: str) -> None
This method simply emits PydanticJsonSchemaWarnings based on handling in the warning_message method.
None
def render_warning_message(kind: JsonSchemaWarningKind, detail: str) -> str | None
This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
You can override the value of ignored_warning_kinds in a subclass of GenerateJsonSchema
to modify what warnings are generated. If you want more control, you can override this method;
just return None in situations where you don’t want warnings to be emitted.
str | None — The formatted warning message, or None if no warning should be emitted.
The kind of warning to render. It can be one of the following:
- ‘skipped-choice’: A choice field was skipped because it had no valid choices.
- ‘non-serializable-default’: A default value was skipped because it was not JSON-serializable.
A string with additional details about the warning.
Bases: Generic[T]
Usage docs: https://docs.pydantic.dev/2.2/usage/type_adapter/
Type adapters provide a flexible way to perform validation and serialization based on a Python type.
A TypeAdapter instance exposes some of the functionality from BaseModel instance methods
for types that do not have such methods (such as dataclasses, primitive types, and more).
Note that TypeAdapter is not an actual type, so you cannot use it in type annotations.
Default: core_schema
Default: validator
Default: serializer
def __new__(cls, __type: type[T], config: ConfigDict | None = ...) -> TypeAdapter[T]
def __new__(cls, __type: T, config: ConfigDict | None = ...) -> TypeAdapter[T]
A class representing the type adapter.
TypeAdapter[T]
def __init__(
type: type[T],
config: ConfigDict | None = None,
_parent_depth: int = 2,
) -> None
def __init__(type: T, config: ConfigDict | None = None, _parent_depth: int = 2) -> None
Initializes the TypeAdapter object.
None
def validate_python(
__object: Any,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate a Python object against the model.
T — The validated object.
The Python object to validate against the model.
Whether to strictly check types.
Whether to extract data from object attributes.
Additional context to pass to the validator.
def validate_json(
__data: str | bytes,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate a JSON string or bytes against the model.
T — The validated object.
The JSON data to validate against the model.
Whether to strictly check types.
Additional context to use during validation.
def get_default_value(
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Some[T] | None
Get the default value for the wrapped type.
Some[T] | None — The default value wrapped in a Some if there is one or None if not.
Whether to strictly check types.
Additional context to pass to the validator.
def dump_python(
__instance: T,
mode: Literal['json', 'python'] = 'python',
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> Any
Dump an instance of the adapted type to a Python object.
Any — The serialized object.
The Python object to serialize.
The output format.
Fields to include in the output.
Fields to exclude from the output.
Whether to use alias names for field names.
Whether to exclude unset fields.
Whether to exclude fields with default values.
Whether to exclude fields with None values.
Whether to output the serialized data in a way that is compatible with deserialization.
Whether to display serialization warnings.
def dump_json(
__instance: T,
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> bytes
Serialize an instance of the adapted type to JSON.
bytes — The JSON representation of the given instance as bytes.
The instance to be serialized.
Number of spaces for JSON indentation.
Fields to include.
Fields to exclude.
Whether to use alias names for field names.
Whether to exclude unset fields.
Whether to exclude fields with default values.
Whether to exclude fields with a value of None.
Whether to serialize and deserialize the instance to ensure round-tripping.
Whether to emit serialization warnings.
def json_schema(
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]
Generate a JSON schema for the adapted type.
dict[str, Any] — The JSON schema for the model as a dictionary.
Whether to use alias names for field names.
The format string used for generating $ref strings.
The generator class used for creating the schema.
The mode to use for schema generation.
@staticmethod
def json_schemas(
__inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]],
by_alias: bool = True,
title: str | None = None,
description: str | None = None,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
Generate a JSON schema including definitions from multiple type adapters.
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue] — A tuple where:
- The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have JsonRef references to definitions that are defined in the second returned element.)
- The second element is a JSON schema containing all definitions referenced in the first returned element, along with the optional title and description keys.
Inputs to schema generation. The first two items will form the keys of the (first) output mapping; the type adapters will provide the core schemas that get converted into definitions in the output JSON schema.
Whether to use alias names.
The title for the schema.
The description for the schema.
The format string used for generating $ref strings.
The generator class used for creating the schema.
The default format string used to generate reference names.
Default: '#/$defs/\{model\}'
Default: TypeVar('JsonSchemaKeyT', bound=Hashable)
A type alias that represents the mode of a JSON schema; either ‘validation’ or ‘serialization’.
For some types, the inputs to validation differ from the outputs of serialization. For example, computed fields will only be present when serializing, and should not be provided when validating. This flag provides a way to indicate whether you want the JSON schema required for validation inputs, or that will be matched by serialization outputs.
Default: Literal['validation', 'serialization']
A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary values.
Default: Dict[str, Any]
Default: TypeVar('T')
Default: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]]