pydantic_core
SchemaValidator ¶
SchemaValidator
is the Python wrapper for pydantic-core
's Rust validation logic, internally it owns one
CombinedValidator
which may in turn own more CombinedValidator
s which make up the full schema validator.
title
property
¶
title: str
The title of the schema, as used in the heading of ValidationError.__str__()
.
validate_python ¶
validate_python(
input,
*,
strict=None,
from_attributes=None,
context=None,
self_instance=None
)
Validate a Python object against the schema and return the validated object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input |
Any
|
The Python object to validate. |
required |
strict |
bool | None
|
Whether to validate the object in strict mode.
If |
None
|
from_attributes |
bool | None
|
Whether to validate objects as inputs to models by extracting attributes.
If |
None
|
context |
'dict[str, Any] | None'
|
The context to use for validation, this is passed to functional validators as
|
None
|
self_instance |
Any | None
|
An instance of a model set attributes on from validation, this is used when running
validation from the |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If validation fails. |
Exception
|
Other error types maybe raised if internal errors occur. |
Returns:
Type | Description |
---|---|
Any
|
The validated object. |
isinstance_python ¶
isinstance_python(
input,
*,
strict=None,
from_attributes=None,
context=None,
self_instance=None
)
Similar to validate_python()
but returns a boolean.
Arguments match validate_python()
. This method will not raise ValidationError
s but will raise internal
errors.
Returns:
Type | Description |
---|---|
bool
|
|
validate_json ¶
validate_json(
input, *, strict=None, context=None, self_instance=None
)
Validate JSON data directly against the schema and return the validated Python object.
This method should be significantly faster than validate_python(json.loads(json_data))
as it avoids the
need to create intermediate Python objects
It also handles constructing the correct Python type even in strict mode, where
validate_python(json.loads(json_data))
would fail validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input |
str | bytes | bytearray
|
The JSON data to validate. |
required |
strict |
bool | None
|
Whether to validate the object in strict mode.
If |
None
|
context |
'dict[str, Any] | None'
|
The context to use for validation, this is passed to functional validators as
|
None
|
self_instance |
Any | None
|
An instance of a model set attributes on from validation. |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If validation fails or if the JSON data is invalid. |
Exception
|
Other error types maybe raised if internal errors occur. |
Returns:
Type | Description |
---|---|
Any
|
The validated Python object. |
validate_strings ¶
validate_strings(input, *, strict=None, context=None)
Validate a string against the schema and return the validated Python object.
This is similar to validate_json
but applies to scenarios where the input will be a string but not
JSON data, e.g. URL fragments, query parameters, etc.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input |
_StringInput
|
The input as a string, or bytes/bytearray if |
required |
strict |
bool | None
|
Whether to validate the object in strict mode.
If |
None
|
context |
'dict[str, Any] | None'
|
The context to use for validation, this is passed to functional validators as
|
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If validation fails or if the JSON data is invalid. |
Exception
|
Other error types maybe raised if internal errors occur. |
Returns:
Type | Description |
---|---|
Any
|
The validated Python object. |
validate_assignment ¶
validate_assignment(
obj,
field_name,
field_value,
*,
strict=None,
from_attributes=None,
context=None
)
Validate an assignment to a field on a model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj |
Any
|
The model instance being assigned to. |
required |
field_name |
str
|
The name of the field to validate assignment for. |
required |
field_value |
Any
|
The value to assign to the field. |
required |
strict |
bool | None
|
Whether to validate the object in strict mode.
If |
None
|
from_attributes |
bool | None
|
Whether to validate objects as inputs to models by extracting attributes.
If |
None
|
context |
'dict[str, Any] | None'
|
The context to use for validation, this is passed to functional validators as
|
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If validation fails. |
Exception
|
Other error types maybe raised if internal errors occur. |
Returns:
Type | Description |
---|---|
dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]
|
Either the model dict or a tuple of |
get_default_value ¶
get_default_value(*, strict=None, context=None)
Get the default value for the schema, including running default value validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict |
bool | None
|
Whether to validate the default value in strict mode.
If |
None
|
context |
Any
|
The context to use for validation, this is passed to functional validators as
|
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If validation fails. |
Exception
|
Other error types maybe raised if internal errors occur. |
Returns:
Type | Description |
---|---|
Some | None
|
|
SchemaSerializer ¶
SchemaSerializer
is the Python wrapper for pydantic-core
's Rust serialization logic, internally it owns one
CombinedSerializer
which may in turn own more CombinedSerializer
s which make up the full schema serializer.
to_python ¶
to_python(
value,
*,
mode=None,
include=None,
exclude=None,
by_alias=True,
exclude_unset=False,
exclude_defaults=False,
exclude_none=False,
round_trip=False,
warnings=True,
fallback=None
)
Serialize/marshal a Python object to a Python object including transforming and filtering data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Any
|
The Python object to serialize. |
required |
mode |
str | None
|
The serialization mode to use, either |
None
|
include |
_IncEx
|
A set of fields to include, if |
None
|
exclude |
_IncEx
|
A set of fields to exclude, if |
None
|
by_alias |
bool
|
Whether to use the alias names of fields. |
True
|
exclude_unset |
bool
|
Whether to exclude fields that are not set,
e.g. are not included in |
False
|
exclude_defaults |
bool
|
Whether to exclude fields that are equal to their default value. |
False
|
exclude_none |
bool
|
Whether to exclude fields that have a value of |
False
|
round_trip |
bool
|
Whether to enable serialization and validation round-trip support. |
False
|
warnings |
bool
|
Whether to log warnings when invalid fields are encountered. |
True
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
Any
|
The serialized Python object. |
to_json ¶
to_json(
value,
*,
indent=None,
include=None,
exclude=None,
by_alias=True,
exclude_unset=False,
exclude_defaults=False,
exclude_none=False,
round_trip=False,
warnings=True,
fallback=None
)
Serialize a Python object to JSON including transforming and filtering data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Any
|
The Python object to serialize. |
required |
indent |
int | None
|
If |
None
|
include |
_IncEx
|
A set of fields to include, if |
None
|
exclude |
_IncEx
|
A set of fields to exclude, if |
None
|
by_alias |
bool
|
Whether to use the alias names of fields. |
True
|
exclude_unset |
bool
|
Whether to exclude fields that are not set,
e.g. are not included in |
False
|
exclude_defaults |
bool
|
Whether to exclude fields that are equal to their default value. |
False
|
exclude_none |
bool
|
Whether to exclude fields that have a value of |
False
|
round_trip |
bool
|
Whether to enable serialization and validation round-trip support. |
False
|
warnings |
bool
|
Whether to log warnings when invalid fields are encountered. |
True
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
bytes
|
JSON bytes. |
ValidationError ¶
Bases: ValueError
ValidationError
is the exception raised by pydantic-core
when validation fails, it contains a list of errors
which detail why validation failed.
title
property
¶
title: str
The title of the error, as used in the heading of str(validation_error)
.
from_exception_data
staticmethod
¶
from_exception_data(
title,
line_errors,
input_type="python",
hide_input=False,
)
Python constructor for a Validation Error.
The API for constructing validation errors will probably change in the future,
hence the static method rather than __init__
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title |
str
|
The title of the error, as used in the heading of |
required |
line_errors |
list[InitErrorDetails]
|
A list of |
required |
input_type |
Literal['python', 'json']
|
Whether the error is for a Python object or JSON. |
'python'
|
hide_input |
bool
|
Whether to hide the input value in the error message. |
False
|
error_count ¶
error_count()
Returns:
Type | Description |
---|---|
int
|
The number of errors in the validation error. |
errors ¶
errors(
*,
include_url=True,
include_context=True,
include_input=True
)
Details about each error in the validation error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include_url |
bool
|
Whether to include a URL to documentation on the error each error. |
True
|
include_context |
bool
|
Whether to include the context of each error. |
True
|
include_input |
bool
|
Whether to include the input value of each error. |
True
|
Returns:
Type | Description |
---|---|
list[ErrorDetails]
|
A list of |
json ¶
json(
*,
indent=None,
include_url=True,
include_context=True,
include_input=True
)
Same as errors()
but returns a JSON string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indent |
int | None
|
The number of spaces to indent the JSON by, or |
None
|
include_url |
bool
|
Whether to include a URL to documentation on the error each error. |
True
|
include_context |
bool
|
Whether to include the context of each error. |
True
|
include_input |
bool
|
Whether to include the input value of each error. |
True
|
Returns:
Type | Description |
---|---|
str
|
a JSON string. |
ErrorDetails ¶
Bases: _TypedDict
type
instance-attribute
¶
type: str
The type of error that occurred, this is an identifier designed for programmatic use that will change rarely or never.
type
is unique for each error message, and can hence be used as an identifier to build custom error messages.
loc
instance-attribute
¶
loc: tuple[int | str, ...]
Tuple of strings and ints identifying where in the schema the error occurred.
ctx
instance-attribute
¶
ctx: _NotRequired[dict[str, _Any]]
Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward.
InitErrorDetails ¶
Bases: _TypedDict
type
instance-attribute
¶
type: str | PydanticCustomError
The type of error that occurred, this should a "slug" identifier that changes rarely or never.
loc
instance-attribute
¶
loc: _NotRequired[tuple[int | str, ...]]
Tuple of strings and ints identifying where in the schema the error occurred.
ctx
instance-attribute
¶
ctx: _NotRequired[dict[str, _Any]]
Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward.
SchemaError ¶
Bases: Exception
Information about errors that occur while building a SchemaValidator
or SchemaSerializer
.
errors ¶
errors()
Returns:
Type | Description |
---|---|
list[ErrorDetails]
|
A list of |
PydanticCustomError ¶
Bases: ValueError
PydanticKnownError ¶
Bases: ValueError
PydanticOmit ¶
Bases: Exception
PydanticSerializationError ¶
Bases: ValueError
PydanticSerializationUnexpectedValue ¶
Bases: ValueError
Url ¶
Bases: SupportsAllComparisons
A URL type, internal logic uses the url rust crate originally developed by Mozilla.
scheme
property
¶
scheme: str
The scheme part of the URL.
e.g. https
in https://user:pass@host:port/path?query#fragment
username
property
¶
username: str | None
The username part of the URL, or None
.
e.g. user
in https://user:pass@host:port/path?query#fragment
password
property
¶
password: str | None
The password part of the URL, or None
.
e.g. pass
in https://user:pass@host:port/path?query#fragment
host
property
¶
host: str | None
The host part of the URL, or None
.
If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is https://£££.com
,
host
will be xn--9aaa.com
port
property
¶
port: int | None
The port part of the URL, or None
.
e.g. port
in https://user:pass@host:port/path?query#fragment
path
property
¶
path: str | None
The path part of the URL, or None
.
e.g. /path
in https://user:pass@host:port/path?query#fragment
query
property
¶
query: str | None
The query part of the URL, or None
.
e.g. query
in https://user:pass@host:port/path?query#fragment
fragment
property
¶
fragment: str | None
The fragment part of the URL, or None
.
e.g. fragment
in https://user:pass@host:port/path?query#fragment
unicode_host ¶
unicode_host()
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
query_params ¶
query_params()
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_string ¶
unicode_string()
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
build
classmethod
¶
build(
*,
scheme,
username=None,
password=None,
host,
port=None,
path=None,
query=None,
fragment=None
)
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 |
MultiHostUrl ¶
Bases: SupportsAllComparisons
A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. https://foo.com,bar.com/path
.
Internal URL logic uses the url rust crate originally developed by Mozilla.
scheme
property
¶
scheme: str
The scheme part of the URL.
e.g. https
in https://foo.com,bar.com/path?query#fragment
path
property
¶
path: str | None
The path part of the URL, or None
.
e.g. /path
in https://foo.com,bar.com/path?query#fragment
query
property
¶
query: str | None
The query part of the URL, or None
.
e.g. query
in https://foo.com,bar.com/path?query#fragment
fragment
property
¶
fragment: str | None
The fragment part of the URL, or None
.
e.g. fragment
in https://foo.com,bar.com/path?query#fragment
query_params ¶
query_params()
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
hosts ¶
hosts()
The hosts of the MultiHostUrl
as MultiHostHost
typed dicts.
from pydantic_core import MultiHostUrl
mhu = MultiHostUrl('https://foo.com:123,foo:[email protected]/path')
print(mhu.hosts())
"""
[
{'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
{'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
]
Returns:
Type | Description |
---|---|
list[MultiHostHost]
|
A list of dicts, each representing a host. |
unicode_string ¶
unicode_string()
The URL as a unicode string, unlike __str__()
this will not punycode encode the hosts.
build
classmethod
¶
build(
*,
scheme,
hosts=None,
username=None,
password=None,
host=None,
port=None,
path=None,
query=None,
fragment=None
)
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 |
MultiHostHost ¶
Bases: _TypedDict
A host part of a multi-host URL.
ArgsKwargs ¶
Some ¶
Bases: Generic[_T]
Similar to Rust's Option::Some
type, this
identifies a value as being present, and provides a way to access it.
Generally used in a union with None
to different between "some value which could be None" and no value.
TzInfo ¶
Bases: datetime.tzinfo
ErrorTypeInfo ¶
Bases: _TypedDict
Gives information about errors.
type
instance-attribute
¶
type: ErrorType
The type of error that occurred, this should a "slug" identifier that changes rarely or never.
message_template_python
instance-attribute
¶
message_template_python: str
String template to render a human readable error message from using context, when the input is Python.
example_message_python
instance-attribute
¶
example_message_python: str
Example of a human readable error message, when the input is Python.
message_template_json
instance-attribute
¶
message_template_json: _NotRequired[str]
String template to render a human readable error message from using context, when the input is JSON data.
example_message_json
instance-attribute
¶
example_message_json: _NotRequired[str]
Example of a human readable error message, when the input is JSON data.
example_context
instance-attribute
¶
example_context: dict[str, _Any] | None
Example of context values.
to_json ¶
to_json(
value,
*,
indent=None,
include=None,
exclude=None,
by_alias=True,
exclude_none=False,
round_trip=False,
timedelta_mode="iso8601",
bytes_mode="utf8",
serialize_unknown=False,
fallback=None
)
Serialize a Python object to JSON including transforming and filtering data.
This is effectively a standalone version of SchemaSerializer.to_json
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Any
|
The Python object to serialize. |
required |
indent |
int | None
|
If |
None
|
include |
_IncEx
|
A set of fields to include, if |
None
|
exclude |
_IncEx
|
A set of fields to exclude, if |
None
|
by_alias |
bool
|
Whether to use the alias names of fields. |
True
|
exclude_none |
bool
|
Whether to exclude fields that have a value of |
False
|
round_trip |
bool
|
Whether to enable serialization and validation round-trip support. |
False
|
timedelta_mode |
Literal['iso8601', 'float']
|
How to serialize |
'iso8601'
|
bytes_mode |
Literal['utf8', 'base64']
|
How to serialize |
'utf8'
|
serialize_unknown |
bool
|
Attempt to serialize unknown types, |
False
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
bytes
|
JSON bytes. |
to_jsonable_python ¶
to_jsonable_python(
value,
*,
include=None,
exclude=None,
by_alias=True,
exclude_none=False,
round_trip=False,
timedelta_mode="iso8601",
bytes_mode="utf8",
serialize_unknown=False,
fallback=None
)
Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.
This is effectively a standalone version of
SchemaSerializer.to_python(mode='json')
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
Any
|
The Python object to serialize. |
required |
include |
_IncEx
|
A set of fields to include, if |
None
|
exclude |
_IncEx
|
A set of fields to exclude, if |
None
|
by_alias |
bool
|
Whether to use the alias names of fields. |
True
|
exclude_none |
bool
|
Whether to exclude fields that have a value of |
False
|
round_trip |
bool
|
Whether to enable serialization and validation round-trip support. |
False
|
timedelta_mode |
Literal['iso8601', 'float']
|
How to serialize |
'iso8601'
|
bytes_mode |
Literal['utf8', 'base64']
|
How to serialize |
'utf8'
|
serialize_unknown |
bool
|
Attempt to serialize unknown types, |
False
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
Any
|
The serialized Python object. |