Miscellaneous
plateforme.core.schema.json
This module provides utilities for managing JSON schema within the Plateforme framework using Pydantic features.
DEFAULT_REF_TEMPLATE
module-attribute
The default format string for generating reference names in JSON schemas.
JsonEncoder
module-attribute
A type alias for the JSON encoder function.
JsonSchemaDict
module-attribute
A type alias for a JSON schema dictionary.
JsonSchemaExtra
module-attribute
JsonSchemaExtra = Union[
JsonSchemaDict, Callable[[JsonSchemaDict], None]
]
A type alias for the extra JSON schema data.
JsonSchemaExtraCallable
module-attribute
JsonSchemaExtraCallable = Union[
JsonSchemaExtra,
Callable[[JsonSchemaDict, Type[Any]], None],
]
A type alias for the extra JSON schema data callable.
JsonSchemaMode
module-attribute
JsonSchemaMode = Literal['validation', 'serialization']
A type alias for the mode of a JSON schema.
For some types, the inputs for 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.
JsonSchemaSource
module-attribute
JsonSchemaSource = Literal['key', 'model', 'both']
A type alias for the source of a JSON schema.
It describes the source type to use for generating the resources JSON schema.
It can be either key
, model
, or both
where the latter accepts,
when applicable, integer and string values for key identifiers in addition to
the standard model schema generation.
JsonSchemaValue
module-attribute
A type alias for a JSON schema value.
GenerateJsonSchema
GenerateJsonSchema(
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
)
Bases: GenerateJsonSchema
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, ref_template
to format reference names and source
to determine
the source type of the schema when applicable.
Attributes:
Name | Type | Description |
---|---|---|
schema_dialect |
The JSON schema dialect used to generate the schema. |
|
ignored_warning_kinds |
set[JsonSchemaWarningKind]
|
Warnings to ignore when generating the schema.
A |
by_alias |
Whether to use field aliases when generating the schema, i.e.
if |
|
ref_template |
The template format string to use when generating
reference names. Defaults to |
|
source |
The source type of the schema. It can be either |
|
core_to_json_refs |
dict[CoreModeRef, JsonRef]
|
A mapping of core refs to JSON refs. |
core_to_defs_refs |
dict[CoreModeRef, DefsRef]
|
A mapping of core refs to definition refs. |
defs_to_core_refs |
dict[DefsRef, CoreModeRef]
|
A mapping of definition refs to core refs. |
json_to_defs_refs |
dict[JsonRef, DefsRef]
|
A mapping of JSON refs to definition refs. |
definitions |
dict[DefsRef, JsonSchemaValue]
|
Definitions in the schema. |
Raises:
Type | Description |
---|---|
JsonSchemaError
|
If the instance of the class is inadvertently re-used after generating a schema. |
Note
See documentation bellow for more information about schema dialects: https://json-schema.org/understanding-json-schema/reference/schema.html
Initialize the JSON schema generator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by_alias
|
bool
|
Whether to use field aliases when generating the schema,
i.e. if |
True
|
ref_template
|
str
|
The template format string to use when generating
reference names. Defaults to |
DEFAULT_REF_TEMPLATE
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/json.py
ValidationsMapping
This class just contains mappings from core_schema attribute names to the corresponding JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in principle override this class in a subclass of GenerateJsonSchema (by inheriting from GenerateJsonSchema.ValidationsMapping) to change these mappings.
build_schema_type_to_method
build_schema_type_to_method() -> dict[
CoreSchemaOrFieldType,
Callable[[CoreSchemaOrField], JsonSchemaValue],
]
Builds a dictionary mapping fields to methods for generating JSON schemas.
Returns:
Type | Description |
---|---|
dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]
|
A dictionary containing the mapping of |
Raises:
Type | Description |
---|---|
TypeError
|
If no method has been defined for generating a JSON schema for a given pydantic core schema type. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
generate_definitions
generate_definitions(
inputs: Sequence[
tuple[JsonSchemaKeyT, JsonSchemaMode, 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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inputs
|
Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, CoreSchema]]
|
A sequence of tuples, where:
|
required |
Returns:
Type | Description |
---|---|
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]
|
A tuple where:
|
Raises:
Type | Description |
---|---|
PydanticUserError
|
Raised if the JSON schema generator has already been used to generate a JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
generate_inner
generate_inner(
schema: CoreSchemaOrField,
) -> JsonSchemaValue
Generates a JSON schema for a given core schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CoreSchemaOrField
|
The given core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
|
any_schema
any_schema(schema: AnySchema) -> JsonSchemaValue
Generates a JSON schema that matches any value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
AnySchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
none_schema
none_schema(schema: NoneSchema) -> JsonSchemaValue
Generates a JSON schema that matches None
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
NoneSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
bool_schema
bool_schema(schema: BoolSchema) -> JsonSchemaValue
Generates a JSON schema that matches a bool value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
BoolSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
int_schema
int_schema(schema: IntSchema) -> JsonSchemaValue
Generates a JSON schema that matches an int value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
IntSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
float_schema
float_schema(schema: FloatSchema) -> JsonSchemaValue
Generates a JSON schema that matches a float value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
FloatSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
decimal_schema
decimal_schema(schema: DecimalSchema) -> JsonSchemaValue
Generates a JSON schema that matches a decimal value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DecimalSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
str_schema
str_schema(schema: StringSchema) -> JsonSchemaValue
Generates a JSON schema that matches a string value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
StringSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
bytes_schema
bytes_schema(schema: BytesSchema) -> JsonSchemaValue
Generates a JSON schema that matches a bytes value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
BytesSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
date_schema
date_schema(schema: DateSchema) -> JsonSchemaValue
Generates a JSON schema that matches a date value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DateSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
time_schema
time_schema(schema: TimeSchema) -> JsonSchemaValue
Generates a JSON schema that matches a time value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TimeSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
datetime_schema
datetime_schema(schema: DatetimeSchema) -> JsonSchemaValue
Generates a JSON schema that matches a datetime value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DatetimeSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
timedelta_schema
timedelta_schema(
schema: TimedeltaSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a timedelta value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TimedeltaSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
literal_schema
literal_schema(schema: LiteralSchema) -> JsonSchemaValue
Generates a JSON schema that matches a literal value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
LiteralSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
is_instance_schema
is_instance_schema(
schema: IsInstanceSchema,
) -> JsonSchemaValue
Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
Unless overridden in a subclass, this raises an error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
IsInstanceSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
is_subclass_schema
is_subclass_schema(
schema: IsSubclassSchema,
) -> JsonSchemaValue
Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
IsSubclassSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
callable_schema
callable_schema(schema: CallableSchema) -> JsonSchemaValue
Generates a JSON schema that matches a callable value.
Unless overridden in a subclass, this raises an error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CallableSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
list_schema
list_schema(schema: ListSchema) -> JsonSchemaValue
Returns a schema that matches a list schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ListSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
tuple_positional_schema
tuple_positional_schema(
schema: TupleSchema,
) -> JsonSchemaValue
Replaced by tuple_schema
.
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
tuple_variable_schema
tuple_variable_schema(
schema: TupleSchema,
) -> JsonSchemaValue
Replaced by tuple_schema
.
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
tuple_schema
tuple_schema(schema: TupleSchema) -> JsonSchemaValue
Generates a JSON schema that matches a tuple schema e.g. Tuple[int,
str, bool]
or Tuple[int, ...]
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TupleSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
set_schema
set_schema(schema: SetSchema) -> JsonSchemaValue
Generates a JSON schema that matches a set schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
SetSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
frozenset_schema
frozenset_schema(
schema: FrozenSetSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a frozenset schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
FrozenSetSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
generator_schema
generator_schema(
schema: GeneratorSchema,
) -> JsonSchemaValue
Returns a JSON schema that represents the provided GeneratorSchema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
GeneratorSchema
|
The schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
dict_schema
dict_schema(schema: DictSchema) -> JsonSchemaValue
Generates a JSON schema that matches a dict schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DictSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
function_before_schema
function_before_schema(
schema: BeforeValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-before schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
BeforeValidatorFunctionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
function_after_schema
function_after_schema(
schema: AfterValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-after schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
AfterValidatorFunctionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
function_plain_schema
function_plain_schema(
schema: PlainValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-plain schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
PlainValidatorFunctionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
function_wrap_schema
function_wrap_schema(
schema: WrapValidatorFunctionSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a function-wrap schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
WrapValidatorFunctionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
default_schema
default_schema(
schema: WithDefaultSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema with a default value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
WithDefaultSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
nullable_schema
nullable_schema(schema: NullableSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows null values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
NullableSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
union_schema
union_schema(schema: UnionSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
UnionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
tagged_union_schema
tagged_union_schema(
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TaggedUnionSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
chain_schema
chain_schema(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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ChainSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
lax_or_strict_schema
lax_or_strict_schema(
schema: LaxOrStrictSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that allows values matching either the lax schema or the strict schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
LaxOrStrictSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
json_or_python_schema
json_or_python_schema(
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
JsonOrPythonSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
typed_dict_schema
typed_dict_schema(
schema: TypedDictSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a typed dict.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TypedDictSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
typed_dict_field_schema
typed_dict_field_schema(
schema: TypedDictField,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a typed dict field.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
TypedDictField
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
dataclass_field_schema
dataclass_field_schema(
schema: DataclassField,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass field.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DataclassField
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
model_field_schema
model_field_schema(schema: ModelField) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model field.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ModelField
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
computed_field_schema
computed_field_schema(
schema: ComputedField,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a computed field.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ComputedField
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
model_schema
model_schema(schema: ModelSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ModelSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
resolve_schema_to_update
resolve_schema_to_update(
json_schema: JsonSchemaValue,
) -> JsonSchemaValue
Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_schema
|
JsonSchemaValue
|
The schema to resolve. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The resolved schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
model_fields_schema
model_fields_schema(
schema: ModelFieldsSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a model's fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ModelFieldsSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
field_is_present
field_is_present(field: CoreSchemaField) -> bool
Whether the field should be included in the generated JSON schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
field
|
CoreSchemaField
|
The schema for the field itself. |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
field_is_required
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.).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
field
|
ModelField | DataclassField | TypedDictField
|
The schema for the field itself. |
required |
total
|
bool
|
Only applies to |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
dataclass_args_schema
dataclass_args_schema(
schema: DataclassArgsSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DataclassArgsSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
dataclass_schema
dataclass_schema(
schema: DataclassSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a dataclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DataclassSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
arguments_schema
arguments_schema(
schema: ArgumentsSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function's arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
ArgumentsSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
kw_arguments_schema
kw_arguments_schema(
arguments: list[ArgumentsParameter],
var_kwargs_schema: CoreSchema | None,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function's keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
arguments
|
list[ArgumentsParameter]
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
p_arguments_schema
p_arguments_schema(
arguments: list[ArgumentsParameter],
var_args_schema: CoreSchema | None,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function's positional arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
arguments
|
list[ArgumentsParameter]
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
get_argument_name
get_argument_name(argument: ArgumentsParameter) -> str
Retrieves the name of an argument.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
argument
|
ArgumentsParameter
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
str
|
The name of the argument. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
call_schema
call_schema(schema: CallSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a function call.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CallSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
custom_error_schema
custom_error_schema(
schema: CustomErrorSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a custom error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CustomErrorSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
json_schema
json_schema(schema: JsonSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a JSON object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
JsonSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
url_schema
url_schema(schema: UrlSchema) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a URL.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
UrlSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
multi_host_url_schema
multi_host_url_schema(
schema: MultiHostUrlSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
MultiHostUrlSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
uuid_schema
uuid_schema(schema: UuidSchema) -> JsonSchemaValue
Generates a JSON schema that matches a UUID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
UuidSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
definitions_schema
definitions_schema(
schema: DefinitionsSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that defines a JSON object with definitions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DefinitionsSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
definition_ref_schema
definition_ref_schema(
schema: DefinitionReferenceSchema,
) -> JsonSchemaValue
Generates a JSON schema that matches a schema that references a definition.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
DefinitionReferenceSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
ser_schema
ser_schema(
schema: SerSchema
| IncExSeqSerSchema
| IncExDictSerSchema,
) -> JsonSchemaValue | None
Generates a JSON schema that matches a schema that defines a serialized object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
SerSchema | IncExSeqSerSchema | IncExDictSerSchema
|
The core schema. |
required |
Returns:
Type | Description |
---|---|
JsonSchemaValue | None
|
The generated JSON schema. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
get_title_from_name
field_title_should_be_set
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).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CoreSchemaOrField
|
The schema to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
|
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
normalize_name
get_defs_ref
Override this method to change the way that definitions keys are generated from a core reference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
core_mode_ref
|
CoreModeRef
|
The core reference. |
required |
Returns:
Type | Description |
---|---|
DefsRef
|
The definitions key. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
get_cache_defs_ref_schema
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
core_ref
|
CoreRef
|
The core reference to get the definitions reference for. |
required |
Returns:
Type | Description |
---|---|
tuple[DefsRef, JsonSchemaValue]
|
A tuple of the definitions reference and the JSON schema that will refer to it. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
handle_ref_overrides
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)
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
encode_default
Encode a default value to a JSON-serializable value.
This is used to encode default values for fields in the generated JSON schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dft
|
Any
|
The default value to encode. |
required |
Returns:
Type | Description |
---|---|
Any
|
The encoded default value. |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
update_with_validations
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_schema
|
JsonSchemaValue
|
The JSON schema to update. |
required |
core_schema
|
CoreSchema
|
The core schema to get the validations from. |
required |
mapping
|
dict[str, str]
|
A mapping from core_schema attribute names to the corresponding JSON schema attribute names. |
required |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
get_json_ref_counts
get_json_ref_counts(
json_schema: JsonSchemaValue,
) -> dict[JsonRef, int]
Get all values corresponding to the key '$ref' anywhere in the json_schema.
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
emit_warning
emit_warning(
kind: JsonSchemaWarningKind, detail: str
) -> None
This method simply emits PydanticJsonSchemaWarnings based on handling in the warning_message
method.
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
render_warning_message
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kind
|
JsonSchemaWarningKind
|
The kind of warning to render. It can be one of the following:
|
required |
detail
|
str
|
A string with additional details about the warning. |
required |
Returns:
Type | Description |
---|---|
str | None
|
The formatted warning message, or |
Source code in .venv/lib/python3.12/site-packages/pydantic/json_schema.py
generate
generate(
schema: CoreSchema,
mode: JsonSchemaMode = "validation",
source: JsonSchemaSource = "model",
) -> JsonSchemaDict
Generates a JSON schema for a specified core schema.
It generates a JSON schema for a specified core schema using the configured parameters. The schema is generated based on the specified mode and source type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
CoreSchema
|
A |
required |
mode
|
JsonSchemaMode
|
The mode to use for generating the JSON Schema. It can be
either |
'validation'
|
source
|
JsonSchemaSource
|
The source type to use for generating the resources JSON
schema. It can be either |
'model'
|
Returns:
Type | Description |
---|---|
JsonSchemaDict
|
A generated JSON schema representing the given model core schema. |
Raises:
Type | Description |
---|---|
PydanticUserError
|
If the JSON schema generator has already been used to generate a JSON schema. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/json.py
plateforme.core.schema.types
This module provides utilities for managing schema types within the Plateforme framework using Pydantic features.
PydanticConfigDict
Bases: TypedDict
A TypedDict for configuring Pydantic behaviour.
title
instance-attribute
title: str | None
The title for the generated JSON schema, defaults to the model's name
str_to_lower
instance-attribute
str_to_lower: bool
Whether to convert all characters to lowercase for str types. Defaults to False
.
str_to_upper
instance-attribute
str_to_upper: bool
Whether to convert all characters to uppercase for str types. Defaults to False
.
str_strip_whitespace
instance-attribute
str_strip_whitespace: bool
Whether to strip leading and trailing whitespace for str types.
str_min_length
instance-attribute
str_min_length: int
The minimum length for str types. Defaults to None
.
str_max_length
instance-attribute
str_max_length: int | None
The maximum length for str types. Defaults to None
.
extra
instance-attribute
extra: ExtraValues | None
Whether to ignore, allow, or forbid extra attributes during model initialization. Defaults to 'ignore'
.
You can configure how pydantic handles the attributes that are not defined in the model:
allow
- Allow any extra attributes.forbid
- Forbid any extra attributes.ignore
- Ignore any extra attributes.
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(extra='ignore') # (1)!
name: str
user = User(name='John Doe', age=20) # (2)!
print(user)
#> name='John Doe'
- This is the default behaviour.
- The
age
argument is ignored.
Instead, with extra='allow'
, the age
argument is included:
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(extra='allow')
name: str
user = User(name='John Doe', age=20) # (1)!
print(user)
#> name='John Doe' age=20
- The
age
argument is included.
With extra='forbid'
, an error is raised:
from pydantic import BaseModel, ConfigDict, ValidationError
class User(BaseModel):
model_config = ConfigDict(extra='forbid')
name: str
try:
User(name='John Doe', age=20)
except ValidationError as e:
print(e)
'''
1 validation error for User
age
Extra inputs are not permitted [type=extra_forbidden, input_value=20, input_type=int]
'''
frozen
instance-attribute
frozen: bool
Whether 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
.
Note
On V1, the inverse of this setting was called allow_mutation
, and was True
by default.
populate_by_name
instance-attribute
populate_by_name: 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
.
Note
The name of this configuration setting was changed in v2.0 from
allow_population_by_field_name
to populate_by_name
.
from pydantic import BaseModel, ConfigDict, Field
class User(BaseModel):
model_config = ConfigDict(populate_by_name=True)
name: str = Field(alias='full_name') # (1)!
age: int
user = User(full_name='John Doe', age=20) # (2)!
print(user)
#> name='John Doe' age=20
user = User(name='John Doe', age=20) # (3)!
print(user)
#> name='John Doe' age=20
- The field
'name'
has an alias'full_name'
. - The model is populated by the alias
'full_name'
. - The model is populated by the field name
'name'
.
use_enum_values
instance-attribute
use_enum_values: 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
.
Note
If you have an Optional[Enum]
value that you set a default for, you need to use validate_default=True
for said Field to ensure that the use_enum_values
flag takes effect on the default, as extracting an
enum's value occurs during validation, not serialization.
from enum import Enum
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class SomeEnum(Enum):
FOO = 'foo'
BAR = 'bar'
BAZ = 'baz'
class SomeModel(BaseModel):
model_config = ConfigDict(use_enum_values=True)
some_enum: SomeEnum
another_enum: Optional[SomeEnum] = Field(default=SomeEnum.FOO, validate_default=True)
model1 = SomeModel(some_enum=SomeEnum.BAR)
print(model1.model_dump())
# {'some_enum': 'bar', 'another_enum': 'foo'}
model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
print(model2.model_dump())
#> {'some_enum': 'bar', 'another_enum': 'baz'}
validate_assignment
instance-attribute
validate_assignment: bool
Whether to validate the data when the model is changed. Defaults to False
.
The default behavior of Pydantic is to validate the data when the model is created.
In case the user changes the data after the model is created, the model is not revalidated.
from pydantic import BaseModel
class User(BaseModel):
name: str
user = User(name='John Doe') # (1)!
print(user)
#> name='John Doe'
user.name = 123 # (1)!
print(user)
#> name=123
- The validation happens only when the model is created.
- The validation does not happen when the data is changed.
In case you want to revalidate the model when the data is changed, you can use validate_assignment=True
:
from pydantic import BaseModel, ValidationError
class User(BaseModel, validate_assignment=True): # (1)!
name: str
user = User(name='John Doe') # (2)!
print(user)
#> name='John Doe'
try:
user.name = 123 # (3)!
except ValidationError as e:
print(e)
'''
1 validation error for User
name
Input should be a valid string [type=string_type, input_value=123, input_type=int]
'''
- You can either use class keyword arguments, or
model_config
to setvalidate_assignment=True
. - The validation happens when the model is created.
- The validation also happens when the data is changed.
arbitrary_types_allowed
instance-attribute
arbitrary_types_allowed: bool
Whether arbitrary types are allowed for field types. Defaults to False
.
from pydantic import BaseModel, ConfigDict, ValidationError
# This is not a pydantic model, it's an arbitrary class
class Pet:
def __init__(self, name: str):
self.name = name
class Model(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
pet: Pet
owner: str
pet = Pet(name='Hedwig')
# A simple check of instance type is used to validate the data
model = Model(owner='Harry', pet=pet)
print(model)
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
print(model.pet)
#> <__main__.Pet object at 0x0123456789ab>
print(model.pet.name)
#> Hedwig
print(type(model.pet))
#> <class '__main__.Pet'>
try:
# If the value is not an instance of the type, it's invalid
Model(owner='Harry', pet='Hedwig')
except ValidationError as e:
print(e)
'''
1 validation error for Model
pet
Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
'''
# Nothing in the instance of the arbitrary type is checked
# Here name probably should have been a str, but it's not validated
pet2 = Pet(name=42)
model2 = Model(owner='Harry', pet=pet2)
print(model2)
#> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
print(model2.pet)
#> <__main__.Pet object at 0x0123456789ab>
print(model2.pet.name)
#> 42
print(type(model2.pet))
#> <class '__main__.Pet'>
from_attributes
instance-attribute
from_attributes: bool
Whether to build models and look up discriminators of tagged unions using python object attributes.
loc_by_alias
instance-attribute
loc_by_alias: bool
Whether to use the actual key provided in the data (e.g. alias) for error loc
s rather than the field's name. Defaults to True
.
alias_generator
instance-attribute
alias_generator: (
Callable[[str], str] | AliasGenerator | None
)
A callable that takes a field name and returns an alias for it
or an instance of AliasGenerator
. Defaults to None
.
When using a callable, the alias generator is used for both validation and serialization.
If you want to use different alias generators for validation and serialization, you can use
AliasGenerator
instead.
If data source field names do not match your code style (e. g. CamelCase fields),
you can automatically generate aliases using alias_generator
. Here's an example with
a basic callable:
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_pascal
class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_pascal)
name: str
language_code: str
voice = Voice(Name='Filiz', LanguageCode='tr-TR')
print(voice.language_code)
#> tr-TR
print(voice.model_dump(by_alias=True))
#> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
If you want to use different alias generators for validation and serialization, you can use
AliasGenerator
.
from pydantic import AliasGenerator, BaseModel, ConfigDict
from pydantic.alias_generators import to_camel, to_pascal
class Athlete(BaseModel):
first_name: str
last_name: str
sport: str
model_config = ConfigDict(
alias_generator=AliasGenerator(
validation_alias=to_camel,
serialization_alias=to_pascal,
)
)
athlete = Athlete(firstName='John', lastName='Doe', sport='track')
print(athlete.model_dump(by_alias=True))
#> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
ignored_types
instance-attribute
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 ()
.
allow_inf_nan
instance-attribute
allow_inf_nan: bool
Whether to allow infinity (+inf
an -inf
) and NaN values to float fields. Defaults to True
.
json_schema_extra
instance-attribute
A dict or callable to provide extra JSON schema properties. Defaults to None
.
json_encoders
instance-attribute
A dict
of custom JSON encoders for specific types. Defaults to None
.
Deprecated
This config option is a carryover from v1. We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now. It is still deprecated and will likely be removed in the future.
strict
instance-attribute
strict: bool
(new in V2) If True
, strict validation is applied to all fields on the model.
By default, Pydantic attempts to coerce values to the correct type, when possible.
There are situations in which you may want to disable this behavior, and instead raise an error if a value's type does not match the field's type annotation.
To configure strict mode for all fields on a model, you can set strict=True
on the model.
from pydantic import BaseModel, ConfigDict
class Model(BaseModel):
model_config = ConfigDict(strict=True)
name: str
age: int
See Strict Mode for more details.
See the Conversion Table for more details on how Pydantic converts data in both strict and lax modes.
revalidate_instances
instance-attribute
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
By default, model and dataclass instances are not revalidated during validation.
from typing import List
from pydantic import BaseModel
class User(BaseModel, revalidate_instances='never'): # (1)!
hobbies: List[str]
class SubUser(User):
sins: List[str]
class Transaction(BaseModel):
user: User
my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])
my_user.hobbies = [1] # (2)!
t = Transaction(user=my_user) # (3)!
print(t)
#> user=User(hobbies=[1])
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t)
#> user=SubUser(hobbies=['scuba diving'], sins=['lying'])
revalidate_instances
is set to'never'
by **default.- The assignment is not validated, unless you set
validate_assignment
toTrue
in the model's config. - Since
revalidate_instances
is set tonever
, this is not revalidated.
If you want to revalidate instances during validation, you can set revalidate_instances
to 'always'
in the model's config.
from typing import List
from pydantic import BaseModel, ValidationError
class User(BaseModel, revalidate_instances='always'): # (1)!
hobbies: List[str]
class SubUser(User):
sins: List[str]
class Transaction(BaseModel):
user: User
my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])
my_user.hobbies = [1]
try:
t = Transaction(user=my_user) # (2)!
except ValidationError as e:
print(e)
'''
1 validation error for Transaction
user.hobbies.0
Input should be a valid string [type=string_type, input_value=1, input_type=int]
'''
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t) # (3)!
#> user=User(hobbies=['scuba diving'])
revalidate_instances
is set to'always'
.- The model is revalidated, since
revalidate_instances
is set to'always'
. - Using
'never'
we would have gottenuser=SubUser(hobbies=['scuba diving'], sins=['lying'])
.
It's also possible to set revalidate_instances
to 'subclass-instances'
to only revalidate instances
of subclasses of the model.
from typing import List
from pydantic import BaseModel
class User(BaseModel, revalidate_instances='subclass-instances'): # (1)!
hobbies: List[str]
class SubUser(User):
sins: List[str]
class Transaction(BaseModel):
user: User
my_user = User(hobbies=['reading'])
t = Transaction(user=my_user)
print(t)
#> user=User(hobbies=['reading'])
my_user.hobbies = [1]
t = Transaction(user=my_user) # (2)!
print(t)
#> user=User(hobbies=[1])
my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying'])
t = Transaction(user=my_sub_user)
print(t) # (3)!
#> user=User(hobbies=['scuba diving'])
revalidate_instances
is set to'subclass-instances'
.- This is not revalidated, since
my_user
is not a subclass ofUser
. - Using
'never'
we would have gottenuser=SubUser(hobbies=['scuba diving'], sins=['lying'])
.
ser_json_timedelta
instance-attribute
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.
ser_json_bytes
instance-attribute
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.
ser_json_inf_nan
instance-attribute
The encoding of JSON serialized infinity and NaN float values. Accepts the string values of 'null'
and 'constants'
.
Defaults to 'null'
.
'null'
will serialize infinity and NaN values asnull
.'constants'
will serialize infinity and NaN values asInfinity
andNaN
.
validate_default
instance-attribute
validate_default: bool
Whether to validate default values during validation. Defaults to False
.
validate_return
instance-attribute
validate_return: bool
whether to validate the return value from call validators. Defaults to False
.
protected_namespaces
instance-attribute
A tuple
of strings that prevent model to have field which conflict with them.
Defaults to ('model_', )
).
Pydantic prevents collisions between model attributes and BaseModel
's own methods by
namespacing them with the prefix model_
.
import warnings
from pydantic import BaseModel
warnings.filterwarnings('error') # Raise warnings as errors
try:
class Model(BaseModel):
model_prefixed_field: str
except UserWarning as e:
print(e)
'''
Field "model_prefixed_field" has conflict with protected namespace "model_".
You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.
'''
You can customize this behavior using the protected_namespaces
setting:
import warnings
from pydantic import BaseModel, ConfigDict
warnings.filterwarnings('error') # Raise warnings as errors
try:
class Model(BaseModel):
model_prefixed_field: str
also_protect_field: str
model_config = ConfigDict(
protected_namespaces=('protect_me_', 'also_protect_')
)
except UserWarning as e:
print(e)
'''
Field "also_protect_field" has conflict with protected namespace "also_protect_".
You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_',)`.
'''
While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, an error is raised if there is an actual collision with an existing attribute:
hide_input_in_errors
instance-attribute
hide_input_in_errors: bool
Whether to hide inputs when printing errors. Defaults to False
.
Pydantic shows the input value and type when it raises ValidationError
during the validation.
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
a: str
try:
Model(a=123)
except ValidationError as e:
print(e)
'''
1 validation error for Model
a
Input should be a valid string [type=string_type, input_value=123, input_type=int]
'''
You can hide the input value and type by setting the hide_input_in_errors
config to True
.
defer_build
instance-attribute
defer_build: 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.
plugin_settings
instance-attribute
A dict
of settings for plugins. Defaults to None
.
See Pydantic Plugins for details.
schema_generator
instance-attribute
schema_generator: type[GenerateSchema] | None
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. Defaults to None
.
The GenerateSchema
interface is subject to change, currently only the string_schema
method is public.
See #6737 for details.
json_schema_serialization_defaults_required
instance-attribute
json_schema_serialization_defaults_required: bool
Whether fields with default values should be marked as required in the serialization schema. Defaults to False
.
This ensures that the serialization schema will reflect the fact a field with a default will always be present when serializing the model, even though it is not required for validation.
However, there are scenarios where this may be undesirable — in particular, if you want to share the schema between validation and serialization, and don't mind fields with defaults being marked as not required during serialization. See #7209 for more details.
from pydantic import BaseModel, ConfigDict
class Model(BaseModel):
a: str = 'a'
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
print(Model.model_json_schema(mode='validation'))
'''
{
'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
'title': 'Model',
'type': 'object',
}
'''
print(Model.model_json_schema(mode='serialization'))
'''
{
'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
'required': ['a'],
'title': 'Model',
'type': 'object',
}
'''
json_schema_mode_override
instance-attribute
If not None
, the specified mode will be used to generate the JSON schema regardless of what mode
was passed to
the function call. Defaults to None
.
This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the validation schema.
It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
and serialization that must both be referenced from the same schema; when this happens, we automatically append
-Input
to the definition reference for the validation schema and -Output
to the definition reference for the
serialization schema. By specifying a json_schema_mode_override
though, this prevents the conflict between
the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
from being added to the definition references.
from pydantic import BaseModel, ConfigDict, Json
class Model(BaseModel):
a: Json[int] # requires a string to validate, but will dump an int
print(Model.model_json_schema(mode='serialization'))
'''
{
'properties': {'a': {'title': 'A', 'type': 'integer'}},
'required': ['a'],
'title': 'Model',
'type': 'object',
}
'''
class ForceInputModel(Model):
# the following ensures that even with mode='serialization', we
# will get the schema that would be generated for validation.
model_config = ConfigDict(json_schema_mode_override='validation')
print(ForceInputModel.model_json_schema(mode='serialization'))
'''
{
'properties': {
'a': {
'contentMediaType': 'application/json',
'contentSchema': {'type': 'integer'},
'title': 'A',
'type': 'string',
}
},
'required': ['a'],
'title': 'ForceInputModel',
'type': 'object',
}
'''
coerce_numbers_to_str
instance-attribute
coerce_numbers_to_str: bool
If True
, enables automatic coercion of any Number
type to str
in "lax" (non-strict) mode. Defaults to False
.
Pydantic doesn't allow number types (int
, float
, Decimal
) to be coerced as type str
by default.
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, ValidationError
class Model(BaseModel):
value: str
try:
print(Model(value=42))
except ValidationError as e:
print(e)
'''
1 validation error for Model
value
Input should be a valid string [type=string_type, input_value=42, input_type=int]
'''
class Model(BaseModel):
model_config = ConfigDict(coerce_numbers_to_str=True)
value: str
repr(Model(value=42).value)
#> "42"
repr(Model(value=42.13).value)
#> "42.13"
repr(Model(value=Decimal('42.13')).value)
#> "42.13"
regex_engine
instance-attribute
The regex engine to used for pattern validation
Defaults to 'rust-regex'
.
rust-regex
uses theregex
Rust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.python-re
use there
module, which supports all regex features, but may be slower.
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class Model(BaseModel):
model_config = ConfigDict(regex_engine='python-re')
value: str = Field(pattern=r'^abc(?=def)')
print(Model(value='abcdef').value)
#> abcdef
try:
print(Model(value='abxyzcdef'))
except ValidationError as e:
print(e)
'''
1 validation error for Model
value
String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
'''
validation_error_cause
instance-attribute
validation_error_cause: bool
If True
, python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False
.
Note
Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: pip install exceptiongroup
.
Note
The structure of validation errors are likely to change in future pydantic versions. Pydantic offers no guarantees about the structure of validation errors. Should be used for visual traceback debugging only.
PydanticIPvAnyAddress
Validate an IPv4 or IPv6 address.
from pydantic import BaseModel
from pydantic.networks import IPvAnyAddress
class IpModel(BaseModel):
ip: IPvAnyAddress
print(IpModel(ip='127.0.0.1'))
#> ip=IPv4Address('127.0.0.1')
try:
IpModel(ip='http://www.example.com')
except ValueError as e:
print(e.errors())
'''
[
{
'type': 'ip_any_address',
'loc': ('ip',),
'msg': 'value is not a valid IPv4 or IPv6 address',
'input': 'http://www.example.com',
}
]
'''
PydanticIPvAnyInterface
Validate an IPv4 or IPv6 interface.
PydanticIPvAnyNetwork
Validate an IPv4 or IPv6 network.
UrlConstraints
dataclass
UrlConstraints(
max_length: int | None = None,
allowed_schemes: list[str] | None = None,
host_required: bool | None = None,
default_host: str | None = None,
default_port: int | None = None,
default_path: str | None = None,
)
Bases: PydanticMetadata
Url constraints.
Attributes:
Name | Type | Description |
---|---|---|
max_length |
int | None
|
The maximum length of the url. Defaults to |
allowed_schemes |
list[str] | None
|
The allowed schemes. Defaults to |
host_required |
bool | None
|
Whether the host is required. Defaults to |
default_host |
str | None
|
The default host. Defaults to |
default_port |
int | None
|
The default port. Defaults to |
default_path |
str | None
|
The default path. Defaults to |
TypeAdapter
TypeAdapter(
type: type[T],
*,
config: ConfigDict | None = ...,
_parent_depth: int = ...,
module: str | None = ...,
)
TypeAdapter(
type: T,
*,
config: ConfigDict | None = ...,
_parent_depth: int = ...,
module: str | None = ...,
)
TypeAdapter(
type: type[T] | T,
*,
config: ConfigDict | None = None,
_parent_depth: int = 2,
module: str | None = None,
)
Bases: Generic[T]
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: TypeAdapter
instances are not types, and cannot be used as type annotations for fields.
Attributes:
Name | Type | Description |
---|---|---|
core_schema |
The core schema for the type. |
|
validator |
SchemaValidator
|
The schema validator for the type. |
serializer |
The schema serializer for the type. |
Initializes the TypeAdapter object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
type
|
type[T] | T
|
The type associated with the |
required |
config
|
ConfigDict | None
|
Configuration for the |
None
|
_parent_depth
|
int
|
depth at which to search the parent namespace to construct the local namespace. |
2
|
module
|
str | None
|
The module that passes to plugin if provided. |
None
|
Note
You cannot use the config
argument when instantiating a TypeAdapter
if the type you're using has its own
config that cannot be overridden (ex: BaseModel
, TypedDict
, and dataclass
). A
type-adapter-config-unused
error will be raised in this case.
Note
The _parent_depth
argument is named with an underscore to suggest its private nature and discourage use.
It may be deprecated in a minor version, so we only recommend using it if you're
comfortable with potential change in behavior / support.
Compatibility with mypy
Depending on the type used, mypy
might raise an error when instantiating a TypeAdapter
. As a workaround, you can explicitly
annotate your variable:
Returns:
Type | Description |
---|---|
None
|
A type adapter configured for the specified |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
validate_python
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__object
|
Any
|
The Python object to validate against the model. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from object attributes. |
None
|
context
|
dict[str, Any] | None
|
Additional context to pass to the validator. |
None
|
Note
When using TypeAdapter
with a Pydantic dataclass
, the use of the from_attributes
argument is not supported.
Returns:
Type | Description |
---|---|
T
|
The validated object. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
validate_json
validate_json(
__data: str | bytes,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-parsing
Validate a JSON string or bytes against the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__data
|
str | bytes
|
The JSON data to validate against the model. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to use during validation. |
None
|
Returns:
Type | Description |
---|---|
T
|
The validated object. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
validate_strings
validate_strings(
__obj: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> T
Validate object contains string data against the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__obj
|
Any
|
The object contains string data to validate. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to use during validation. |
None
|
Returns:
Type | Description |
---|---|
T
|
The validated object. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
get_default_value
get_default_value(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Some[T] | None
Get the default value for the wrapped type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Some[T] | None
|
The default value wrapped in a |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
dump_python
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__instance
|
T
|
The Python object to serialize. |
required |
mode
|
Literal['json', 'python']
|
The output format. |
'python'
|
include
|
IncEx | None
|
Fields to include in the output. |
None
|
exclude
|
IncEx | None
|
Fields to exclude from the output. |
None
|
by_alias
|
bool
|
Whether to use alias names for field names. |
False
|
exclude_unset
|
bool
|
Whether to exclude unset fields. |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields with default values. |
False
|
exclude_none
|
bool
|
Whether to exclude fields with None values. |
False
|
round_trip
|
bool
|
Whether to output the serialized data in a way that is compatible with deserialization. |
False
|
warnings
|
bool
|
Whether to display serialization warnings. |
True
|
Returns:
Type | Description |
---|---|
Any
|
The serialized object. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
dump_json
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
Usage docs: https://docs.pydantic.dev/2.6/concepts/json/#json-serialization
Serialize an instance of the adapted type to JSON.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__instance
|
T
|
The instance to be serialized. |
required |
indent
|
int | None
|
Number of spaces for JSON indentation. |
None
|
include
|
IncEx | None
|
Fields to include. |
None
|
exclude
|
IncEx | None
|
Fields to exclude. |
None
|
by_alias
|
bool
|
Whether to use alias names for field names. |
False
|
exclude_unset
|
bool
|
Whether to exclude unset fields. |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields with default values. |
False
|
exclude_none
|
bool
|
Whether to exclude fields with a value of |
False
|
round_trip
|
bool
|
Whether to serialize and deserialize the instance to ensure round-tripping. |
False
|
warnings
|
bool
|
Whether to emit serialization warnings. |
True
|
Returns:
Type | Description |
---|---|
bytes
|
The JSON representation of the given instance as bytes. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
json_schema
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by_alias
|
bool
|
Whether to use alias names for field names. |
True
|
ref_template
|
str
|
The format string used for generating $ref strings. |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The generator class used for creating the schema. |
GenerateJsonSchema
|
mode
|
JsonSchemaMode
|
The mode to use for schema generation. |
'validation'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The JSON schema for the model as a dictionary. |
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
json_schemas
staticmethod
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__inputs
|
Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]]
|
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. |
required |
by_alias
|
bool
|
Whether to use alias names. |
True
|
title
|
str | None
|
The title for the schema. |
None
|
description
|
str | None
|
The description for the schema. |
None
|
ref_template
|
str
|
The format string used for generating $ref strings. |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The generator class used for creating the schema. |
GenerateJsonSchema
|
Returns:
Type | Description |
---|---|
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
|
A tuple where:
|
Source code in .venv/lib/python3.12/site-packages/pydantic/type_adapter.py
AllowInfNan
dataclass
AllowInfNan(allow_inf_nan: bool = True)
Bases: PydanticMetadata
A field metadata class to indicate that a field should allow -inf
, inf
, and nan
.
PydanticAwareDateTime
A datetime that requires timezone info.
Discriminator
dataclass
Discriminator(
discriminator: str | Callable[[Any], Hashable],
custom_error_type: str | None = None,
custom_error_message: str | None = None,
custom_error_context: dict[str, int | str | float]
| None = None,
)
Usage docs: https://docs.pydantic.dev/2.6/concepts/unions/#discriminated-unions-with-callable-discriminator
Provides a way to use a custom callable as the way to extract the value of a union discriminator.
This allows you to get validation behavior like you'd get from Field(discriminator=<field_name>)
,
but without needing to have a single shared field across all the union choices. This also makes it
possible to handle unions of models and primitive types with discriminated-union-style validation errors.
Finally, this allows you to use a custom callable as the way to identify which member of a union a value
belongs to, while still seeing all the performance benefits of a discriminated union.
Consider this example, which is much more performant with the use of Discriminator
and thus a TaggedUnion
than it would be as a normal Union
.
from typing import Any, Union
from typing_extensions import Annotated, Literal
from pydantic import BaseModel, Discriminator, Tag
class Pie(BaseModel):
time_to_cook: int
num_ingredients: int
class ApplePie(Pie):
fruit: Literal['apple'] = 'apple'
class PumpkinPie(Pie):
filling: Literal['pumpkin'] = 'pumpkin'
def get_discriminator_value(v: Any) -> str:
if isinstance(v, dict):
return v.get('fruit', v.get('filling'))
return getattr(v, 'fruit', getattr(v, 'filling', None))
class ThanksgivingDinner(BaseModel):
dessert: Annotated[
Union[
Annotated[ApplePie, Tag('apple')],
Annotated[PumpkinPie, Tag('pumpkin')],
],
Discriminator(get_discriminator_value),
]
apple_variation = ThanksgivingDinner.model_validate(
{'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''
pumpkin_variation = ThanksgivingDinner.model_validate(
{
'dessert': {
'filling': 'pumpkin',
'time_to_cook': 40,
'num_ingredients': 6,
}
}
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''
See the Discriminated Unions concepts docs for more details on how to use Discriminator
s.
discriminator
instance-attribute
The callable or field name for discriminating the type in a tagged union.
A Callable
discriminator must extract the value of the discriminator from the input.
A str
discriminator must be the name of a field to discriminate against.
custom_error_type
class-attribute
instance-attribute
custom_error_type: str | None = None
Type to use in custom errors replacing the standard discriminated union validation errors.
custom_error_message
class-attribute
instance-attribute
custom_error_message: str | None = None
Message to use in custom errors.
PydanticFutureDate
A date in the future.
PydanticFutureDateTime
A datetime that must be in the future.
PydanticNaiveDateTime
A datetime that doesn't require timezone info.
PydanticPastDate
A date in the past.
PydanticPastDateTime
A datetime that must be in the past.
Strict
dataclass
Strict(strict: bool = True)
Bases: PydanticMetadata
, BaseMetadata
Usage docs: https://docs.pydantic.dev/2.6/concepts/strict_mode/#strict-mode-with-annotated-strict
A field metadata class to indicate that a field should be validated in strict mode.
Attributes:
Name | Type | Description |
---|---|---|
strict |
bool
|
Whether to validate the field in strict mode. |
Example
Tag
dataclass
Tag(tag: str)
Provides a way to specify the expected tag to use for a case of a (callable) discriminated union.
Also provides a way to label a union case in error messages.
When using a callable Discriminator
, attach a Tag
to each case in the Union
to specify the tag that
should be used to identify that case. For example, in the below example, the Tag
is used to specify that
if get_discriminator_value
returns 'apple'
, the input should be validated as an ApplePie
, and if it
returns 'pumpkin'
, the input should be validated as a PumpkinPie
.
The primary role of the Tag
here is to map the return value from the callable Discriminator
function to
the appropriate member of the Union
in question.
from typing import Any, Union
from typing_extensions import Annotated, Literal
from pydantic import BaseModel, Discriminator, Tag
class Pie(BaseModel):
time_to_cook: int
num_ingredients: int
class ApplePie(Pie):
fruit: Literal['apple'] = 'apple'
class PumpkinPie(Pie):
filling: Literal['pumpkin'] = 'pumpkin'
def get_discriminator_value(v: Any) -> str:
if isinstance(v, dict):
return v.get('fruit', v.get('filling'))
return getattr(v, 'fruit', getattr(v, 'filling', None))
class ThanksgivingDinner(BaseModel):
dessert: Annotated[
Union[
Annotated[ApplePie, Tag('apple')],
Annotated[PumpkinPie, Tag('pumpkin')],
],
Discriminator(get_discriminator_value),
]
apple_variation = ThanksgivingDinner.model_validate(
{'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''
pumpkin_variation = ThanksgivingDinner.model_validate(
{
'dessert': {
'filling': 'pumpkin',
'time_to_cook': 40,
'num_ingredients': 6,
}
}
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''
Note
You must specify a Tag
for every case in a Tag
that is associated with a
callable Discriminator
. Failing to do so will result in a PydanticUserError
with code
callable-discriminator-no-tag
.
See the Discriminated Unions concepts docs for more details on how to use Tag
s.
UuidVersion
dataclass
A field metadata class to indicate a UUID version.
PydanticMultiHostUrl
build
builtin
build(
*,
scheme: str,
hosts: Optional[list[MultiHostHost]] = None,
path: Optional[str] = None,
query: Optional[str] = None,
fragment: Optional[str] = None,
host: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
port: Optional[int] = None,
) -> Self
Build a new MultiHostUrl
instance from its component parts.
This method takes either hosts
- a list of MultiHostHost
typed dicts, or the individual components
username
, password
, host
and port
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scheme
|
str
|
The scheme part of the URL. |
required |
hosts
|
Optional[list[MultiHostHost]]
|
Multiple hosts to build the URL from. |
None
|
username
|
Optional[str]
|
The username part of the URL. |
None
|
password
|
Optional[str]
|
The password part of the URL. |
None
|
host
|
Optional[str]
|
The host part of the URL. |
None
|
port
|
Optional[int]
|
The port part of the URL. |
None
|
path
|
Optional[str]
|
The path part of the URL. |
None
|
query
|
Optional[str]
|
The query part of the URL, or omit for no query. |
None
|
fragment
|
Optional[str]
|
The fragment part of the URL, or omit for no fragment. |
None
|
Returns:
Type | Description |
---|---|
Self
|
An instance of |
hosts
method descriptor
hosts() -> list[MultiHostHost]
The hosts of the MultiHostUrl
as MultiHostHost
typed dicts.
query_params
method descriptor
The query part of the URL as a list of key-value pairs.
e.g. [('foo', 'bar')]
in https://foo.com,bar.com/path?query#fragment
unicode_string
method descriptor
unicode_string() -> str
The URL as a unicode string, unlike __str__()
this will not punycode encode the hosts.
PydanticUrl
build
builtin
build(
*,
scheme: str,
host: str,
username: Optional[str] = None,
password: Optional[str] = None,
port: Optional[int] = None,
path: Optional[str] = None,
query: Optional[str] = None,
fragment: Optional[str] = None,
) -> Self
Build a new Url
instance from its component parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scheme
|
str
|
The scheme part of the URL. |
required |
username
|
Optional[str]
|
The username part of the URL, or omit for no username. |
None
|
password
|
Optional[str]
|
The password part of the URL, or omit for no password. |
None
|
host
|
str
|
The host part of the URL. |
required |
port
|
Optional[int]
|
The port part of the URL, or omit for no port. |
None
|
path
|
Optional[str]
|
The path part of the URL, or omit for no path. |
None
|
query
|
Optional[str]
|
The query part of the URL, or omit for no query. |
None
|
fragment
|
Optional[str]
|
The fragment part of the URL, or omit for no fragment. |
None
|
Returns:
Type | Description |
---|---|
Self
|
An instance of URL |
query_params
method descriptor
The query part of the URL as a list of key-value pairs.
e.g. [('foo', 'bar')]
in https://user:pass@host:port/path?foo=bar#fragment
unicode_host
method descriptor
unicode_host() -> str | None
The host part of the URL as a unicode string, or None
.
e.g. host
in https://user:pass@host:port/path?query#fragment
If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is https://£££.com
,
unicode_host()
will be £££.com
unicode_string
method descriptor
unicode_string() -> str
The URL as a unicode string, unlike __str__()
this will not punycode encode the host.
If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is https://£££.com
,
unicode_string()
will be https://£££.com
OneOrMany
A class for representing a single value or a sequence of values.
validate
classmethod
Validate the one or many given object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
_T | list[_T] | set[_T] | tuple[_T]
|
The input object to handle either as a single entry or a sequence of entries. If the object is a list, set, or tuple, it will be used as is. Otherwise, it will be wrapped in a list. |
required |
Returns:
Type | Description |
---|---|
OneOrMany[_T]
|
The validated one or many object. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
TypeAdapterList
TypeAdapterList(
type_: type[_T],
*,
config: ConfigDict | None = None,
_parent_depth: int = 2,
module: str | None = None,
)
TypeAdapterList(
type_: _T,
*,
config: ConfigDict | None = None,
_parent_depth: int = 2,
module: str | None = None,
)
TypeAdapterList(
type_: type[_T] | _T,
*,
config: ConfigDict | None = None,
_parent_depth: int = 2,
module: str | None = None,
)
Bases: Generic[_T]
A list type adapter for handling one or many input values.
The type adapters provide a flexible way to perform validation and
serialization based on a Python type. It proxies the TypeAdapter
class
with a list type checking mechanism that allows for a single value or a
sequence of values.
Attributes:
Name | Type | Description |
---|---|---|
core_schema |
The core schema for the type. |
|
validator |
The schema validator for the type. |
|
serializer |
The schema serializer for the type. |
Note
TypeAdapterList
instances are not types, and cannot be used as type
annotations for fields.
Initialize a list type adapter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
type_
|
type[_T] | _T
|
The type associated with the adapter. |
required |
config
|
ConfigDict | None
|
The configuration to use for the adapter. |
None
|
_parent_depth
|
int
|
The depth at which to search the parent namespace to construct the local namespace. |
2
|
module
|
str | None
|
The module that passes to plugin if provided. |
None
|
Returns:
Type | Description |
---|---|
None
|
A type adapter configured for the specified |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
validate_python
validate_python(
__object: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> list[_T]
Validate a Python object against the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__object
|
Any
|
The Python object to validate against the model. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from object attributes. |
None
|
context
|
dict[str, Any] | None
|
Additional context to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
list[_T]
|
The validated object. |
Note
When using TypeAdapterList
with a Pydantic dataclass
, the use
of the from_attributes
argument is not supported.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
validate_json
validate_json(
__data: str | bytes,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> list[_T]
Validate a JSON string or bytes against the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__data
|
str | bytes
|
The JSON data to validate against the model. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to use during validation. |
None
|
Returns:
Type | Description |
---|---|
list[_T]
|
The validated object. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
validate_strings
validate_strings(
__object: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> list[_T]
Validate object contains string data against the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__object
|
Any
|
The object contains string data to validate. |
required |
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to use during validation. |
None
|
Returns:
Type | Description |
---|---|
list[_T]
|
The validated object. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
get_default_value
get_default_value(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Some[list[_T]] | None
Get the default value for the wrapped type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict
|
bool | None
|
Whether to strictly check types. |
None
|
context
|
dict[str, Any] | None
|
Additional context to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Some[list[_T]] | None
|
The default value wrapped in a |
Some[list[_T]] | None
|
if not. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
dump_python
dump_python(
__instances: _T | list[_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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__instances
|
_T | list[_T]
|
The Python object to serialize. |
required |
mode
|
Literal['json', 'python']
|
The output format. |
'python'
|
include
|
IncEx | None
|
Fields to include in the output. |
None
|
exclude
|
IncEx | None
|
Fields to exclude from the output. |
None
|
by_alias
|
bool
|
Whether to use alias names for field names. |
False
|
exclude_unset
|
bool
|
Whether to exclude unset fields. |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields with default values. |
False
|
exclude_none
|
bool
|
Whether to exclude fields with |
False
|
round_trip
|
bool
|
Whether to output the serialized data in a way that is compatible with deserialization. |
False
|
warnings
|
bool
|
Whether to display serialization warnings. |
True
|
Returns:
Type | Description |
---|---|
Any
|
The serialized object. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
dump_json
dump_json(
__instance: _T | list[_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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__instance
|
_T | list[_T]
|
The instance to be serialized. |
required |
indent
|
int | None
|
Number of spaces for JSON indentation. |
None
|
include
|
IncEx | None
|
Fields to include. |
None
|
exclude
|
IncEx | None
|
Fields to exclude. |
None
|
by_alias
|
bool
|
Whether to use alias names for field names. |
False
|
exclude_unset
|
bool
|
Whether to exclude unset fields. |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields with default values. |
False
|
exclude_none
|
bool
|
Whether to exclude fields with a value of |
False
|
round_trip
|
bool
|
Whether to serialize and deserialize the instance to ensure round-tripping. |
False
|
warnings
|
bool
|
Whether to emit serialization warnings. |
True
|
Returns:
Type | Description |
---|---|
bytes
|
The JSON representation of the given instance as bytes. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
json_schema
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by_alias
|
bool
|
Whether to use alias names for field names. |
True
|
ref_template
|
str
|
The format string used for generating $ref strings. |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The generator class used for creating the schema. |
GenerateJsonSchema
|
mode
|
JsonSchemaMode
|
The mode to use for schema generation. |
'validation'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The JSON schema for the model as a dictionary. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/types.py
json_schemas
staticmethod
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 from multiple type adapters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__inputs
|
Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]]
|
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. |
required |
by_alias
|
bool
|
Whether to use alias names. |
True
|
title
|
str | None
|
The title for the schema. |
None
|
description
|
str | None
|
The description for the schema. |
None
|
ref_template
|
str
|
The format string used for generating $ref strings. |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The generator class used for creating the schema. |
GenerateJsonSchema
|
Returns:
Type | Description |
---|---|
dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue]
|
A tuple where: |
JsonSchemaValue
|
|
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
|
|