pydantic_core
SchemaValidator ¶
SchemaValidator(
schema: CoreSchema, config: CoreConfig | None = None
)
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema |
CoreSchema
|
The |
required |
config |
CoreConfig | None
|
Optionally a |
None
|
title
property
¶
title: str
The title of the schema, as used in the heading of ValidationError.__str__()
.
validate_python ¶
validate_python(
input: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None
) -> Any
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 |
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: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None
) -> bool
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: str | bytes | bytearray,
*,
strict: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None
) -> Any
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 |
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: _StringInput,
*,
strict: bool | None = None,
context: Any | None = None
) -> Any
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 |
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: Any,
field_name: str,
field_value: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None
) -> (
dict[str, Any]
| tuple[dict[str, Any], dict[str, Any] | None, set[str]]
)
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 |
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 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(
schema: CoreSchema, config: CoreConfig | None = None
)
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema |
CoreSchema
|
The |
required |
config |
CoreConfig | None
|
Optionally a |
None
|
to_python ¶
to_python(
value: Any,
*,
mode: str | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> Any
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 | None
|
A set of fields to include, if |
None
|
exclude |
_IncEx | None
|
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 | Literal['none', 'warn', 'error']
|
How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
"error" raises a |
True
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
serialize_as_any |
bool
|
Whether to serialize fields with duck-typing serialization behavior. |
False
|
context |
Any | None
|
The context to use for serialization, this is passed to functional serializers as
|
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
Any
|
The serialized Python object. |
to_json ¶
to_json(
value: Any,
*,
indent: int | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> bytes
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 | None
|
A set of fields to include, if |
None
|
exclude |
_IncEx | None
|
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 | Literal['none', 'warn', 'error']
|
How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
"error" raises a |
True
|
fallback |
Callable[[Any], Any] | None
|
A function to call when an unknown value is encountered,
if |
None
|
serialize_as_any |
bool
|
Whether to serialize fields with duck-typing serialization behavior. |
False
|
context |
Any | None
|
The context to use for serialization, this is passed to functional serializers as
|
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: str,
line_errors: list[InitErrorDetails],
input_type: Literal["python", "json"] = "python",
hide_input: bool = False,
) -> ValidationError
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() -> int
Returns:
Type | Description |
---|---|
int
|
The number of errors in the validation error. |
errors ¶
errors(
*,
include_url: bool = True,
include_context: bool = True,
include_input: bool = True
) -> list[ErrorDetails]
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: int | None = None,
include_url: bool = True,
include_context: bool = True,
include_input: bool = True
) -> str
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
¶
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
.
error_count ¶
error_count() -> int
Returns:
Type | Description |
---|---|
int
|
The number of errors in the schema. |
errors ¶
errors() -> list[ErrorDetails]
Returns:
Type | Description |
---|---|
list[ErrorDetails]
|
A list of |
PydanticCustomError ¶
PydanticCustomError(
error_type: LiteralString,
message_template: LiteralString,
context: dict[str, Any] | None = None,
)
Bases: ValueError
A custom exception providing flexible error handling for Pydantic validators.
You can raise this error in custom validators when you'd like flexibility in regards to the error type, message, and context.
Example
from pydantic_core import PydanticCustomError
def custom_validator(v) -> None:
if v <= 10:
raise PydanticCustomError('custom_value_error', 'Value must be greater than {value}', {'value': 10, 'extra_context': 'extra_data'})
return v
Parameters:
Name | Type | Description | Default |
---|---|---|---|
error_type |
LiteralString
|
The error type. |
required |
message_template |
LiteralString
|
The message template. |
required |
context |
dict[str, Any] | None
|
The data to inject into the message template. |
None
|
context
property
¶
Values which are required to render the error message, and could hence be useful in passing error data forward.
type
property
¶
type: str
The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string.
PydanticKnownError ¶
Bases: ValueError
A helper class for raising exceptions that mimic Pydantic's built-in exceptions, with more flexibility in regards to context.
Unlike PydanticCustomError
, the error_type
argument must be a known ErrorType
.
Example
from pydantic_core import PydanticKnownError
def custom_validator(v) -> None:
if v <= 10:
raise PydanticKnownError(error_type='greater_than', context={'gt': 10})
return v
Parameters:
Name | Type | Description | Default |
---|---|---|---|
error_type |
ErrorType
|
The error type. |
required |
context |
dict[str, Any] | None
|
The data to inject into the message template. |
None
|
context
property
¶
Values which are required to render the error message, and could hence be useful in passing error data forward.
PydanticOmit ¶
Bases: Exception
An exception to signal that a field should be omitted from a generated result.
This could span from omitting a field from a JSON Schema to omitting a field from a serialized result. Upcoming: more robust support for using PydanticOmit in custom serializers is still in development. Right now, this is primarily used in the JSON Schema generation process.
Example
from typing import Callable
from pydantic_core import PydanticOmit
from pydantic import BaseModel
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
class MyGenerateJsonSchema(GenerateJsonSchema):
def handle_invalid_for_json_schema(self, schema, error_info) -> JsonSchemaValue:
raise PydanticOmit
class Predicate(BaseModel):
name: str = 'no-op'
func: Callable = lambda x: x
instance_example = Predicate()
validation_schema = instance_example.model_json_schema(schema_generator=MyGenerateJsonSchema, mode='validation')
print(validation_schema)
'''
{'properties': {'name': {'default': 'no-op', 'title': 'Name', 'type': 'string'}}, 'title': 'Predicate', 'type': 'object'}
'''
For a more in depth example / explanation, see the customizing JSON schema docs.
PydanticSerializationError ¶
PydanticSerializationError(message: str)
Bases: ValueError
An error raised when an issue occurs during serialization.
In custom serializers, this error can be used to indicate that serialization has failed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message |
str
|
The message associated with the error. |
required |
PydanticSerializationUnexpectedValue ¶
PydanticSerializationUnexpectedValue(message: str)
Bases: ValueError
An error raised when an unexpected value is encountered during serialization.
This error is often caught and coerced into a warning, as pydantic-core
generally makes a best attempt
at serializing values, in contrast with validation where errors are eagerly raised.
Example
from pydantic import BaseModel, field_serializer
from pydantic_core import PydanticSerializationUnexpectedValue
class BasicPoint(BaseModel):
x: int
y: int
@field_serializer('*')
def serialize(self, v):
if not isinstance(v, int):
raise PydanticSerializationUnexpectedValue(f'Expected type `int`, got {type(v)} with value {v}')
return v
point = BasicPoint(x=1, y=2)
# some sort of mutation
point.x = 'a'
print(point.model_dump())
'''
UserWarning: Pydantic serializer warnings:
PydanticSerializationUnexpectedValue(Expected type `int`, got <class 'str'> with value a)
return self.__pydantic_serializer__.to_python(
{'x': 'a', 'y': 2}
'''
This is often used internally in pydantic-core
when unexpected types are encountered during serialization,
but it can also be used by users in custom serializers, as seen above.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message |
str
|
The message associated with the unexpected value. |
required |
Url ¶
Url(url: str)
Bases: SupportsAllComparisons
A URL type, internal logic uses the url rust crate originally developed by Mozilla.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url |
str
|
String representation of a URL. |
required |
Returns:
Type | Description |
---|---|
None
|
A new |
Raises:
Type | Description |
---|---|
ValidationError
|
If the URL is invalid. |
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() -> 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
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() -> 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
build
classmethod
¶
build(
*,
scheme: str,
username: str | None = None,
password: str | None = None,
host: str,
port: int | None = None,
path: str | None = None,
query: str | None = None,
fragment: str | None = 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 |
str | None
|
The username part of the URL, or omit for no username. |
None
|
password |
str | None
|
The password part of the URL, or omit for no password. |
None
|
host |
str
|
The host part of the URL. |
required |
port |
int | None
|
The port part of the URL, or omit for no port. |
None
|
path |
str | None
|
The path part of the URL, or omit for no path. |
None
|
query |
str | None
|
The query part of the URL, or omit for no query. |
None
|
fragment |
str | None
|
The fragment part of the URL, or omit for no fragment. |
None
|
Returns:
Type | Description |
---|---|
Self
|
An instance of URL |
MultiHostUrl ¶
MultiHostUrl(url: str)
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url |
str
|
String representation of a URL. |
required |
Returns:
Type | Description |
---|---|
None
|
A new |
Raises:
Type | Description |
---|---|
ValidationError
|
If the URL is invalid. |
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 ¶
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() -> list[MultiHostHost]
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}
]
unicode_string ¶
unicode_string() -> str
The URL as a unicode string, unlike __str__()
this will not punycode encode the hosts.
build
classmethod
¶
build(
*,
scheme: str,
hosts: list[MultiHostHost] | None = None,
username: str | None = None,
password: str | None = None,
host: str | None = None,
port: int | None = None,
path: str | None = None,
query: str | None = None,
fragment: str | None = 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 |
list[MultiHostHost] | None
|
Multiple hosts to build the URL from. |
None
|
username |
str | None
|
The username part of the URL. |
None
|
password |
str | None
|
The password part of the URL. |
None
|
host |
str | None
|
The host part of the URL. |
None
|
port |
int | None
|
The port part of the URL. |
None
|
path |
str | None
|
The path part of the URL. |
None
|
query |
str | None
|
The query part of the URL, or omit for no query. |
None
|
fragment |
str | None
|
The fragment part of the URL, or omit for no fragment. |
None
|
Returns:
Type | Description |
---|---|
Self
|
An instance of |
ArgsKwargs ¶
A construct used to store arguments and keyword arguments for a function call.
This data structure is generally used to store information for core schemas associated with functions (like in an arguments schema). This data structure is also currently used for some validation against dataclasses.
Example
from pydantic.dataclasses import dataclass
from pydantic import model_validator
@dataclass
class Model:
a: int
b: int
@model_validator(mode="before")
@classmethod
def no_op_validator(cls, values):
print(values)
return values
Model(1, b=2)
#> ArgsKwargs((1,), {"b": 2})
Model(1, 2)
#> ArgsKwargs((1, 2), {})
Model(a=1, b=2)
#> ArgsKwargs((), {"a": 1, "b": 2})
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args |
tuple[Any, ...]
|
The arguments (inherently ordered) for a function call. |
required |
kwargs |
dict[str, Any] | None
|
The keyword arguments for a function call |
None
|
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: tzinfo
An pydantic-core
implementation of the abstract [datetime.tzinfo
] class.
tzname ¶
Return the time zone name corresponding to the datetime
object dt, as a string.
For more info, see tzinfo.tzname
.
utcoffset ¶
Return offset of local time from UTC, as a timedelta
object that is positive east of UTC. If local time is west of UTC, this should be negative.
More info can be found at tzinfo.utcoffset
.
dst ¶
Return the daylight saving time (DST) adjustment, as a timedelta
object or None
if DST information isn’t known.
More info can be found attzinfo.dst
.
fromutc ¶
Adjust the date and time data associated datetime object dt, returning an equivalent datetime in self’s local time.
More info can be found at tzinfo.fromutc
.
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.
to_json ¶
to_json(
value: Any,
*,
indent: int | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal["iso8601", "float"] = "iso8601",
bytes_mode: Literal["utf8", "base64", "hex"] = "utf8",
inf_nan_mode: Literal[
"null", "constants", "strings"
] = "constants",
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> bytes
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 | None
|
A set of fields to include, if |
None
|
exclude |
_IncEx | None
|
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', 'hex']
|
How to serialize |
'utf8'
|
inf_nan_mode |
Literal['null', 'constants', 'strings']
|
How to serialize |
'constants'
|
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
|
serialize_as_any |
bool
|
Whether to serialize fields with duck-typing serialization behavior. |
False
|
context |
Any | None
|
The context to use for serialization, this is passed to functional serializers as
|
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
bytes
|
JSON bytes. |
from_json ¶
from_json(
data: str | bytes | bytearray,
*,
allow_inf_nan: bool = True,
cache_strings: (
bool | Literal["all", "keys", "none"]
) = True,
allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False
) -> Any
Deserialize JSON data to a Python object.
This is effectively a faster version of json.loads()
, with some extra functionality.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
str | bytes | bytearray
|
The JSON data to deserialize. |
required |
allow_inf_nan |
bool
|
Whether to allow |
True
|
cache_strings |
bool | Literal['all', 'keys', 'none']
|
Whether to cache strings to avoid constructing new Python objects,
this should have a significant impact on performance while increasing memory usage slightly,
|
True
|
allow_partial |
bool | Literal['off', 'on', 'trailing-strings']
|
Whether to allow partial deserialization, if |
False
|
Raises:
Type | Description |
---|---|
ValueError
|
If deserialization fails. |
Returns:
Type | Description |
---|---|
Any
|
The deserialized Python object. |
to_jsonable_python ¶
to_jsonable_python(
value: Any,
*,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal["iso8601", "float"] = "iso8601",
bytes_mode: Literal["utf8", "base64", "hex"] = "utf8",
inf_nan_mode: Literal[
"null", "constants", "strings"
] = "constants",
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> Any
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 | None
|
A set of fields to include, if |
None
|
exclude |
_IncEx | None
|
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', 'hex']
|
How to serialize |
'utf8'
|
inf_nan_mode |
Literal['null', 'constants', 'strings']
|
How to serialize |
'constants'
|
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
|
serialize_as_any |
bool
|
Whether to serialize fields with duck-typing serialization behavior. |
False
|
context |
Any | None
|
The context to use for serialization, this is passed to functional serializers as
|
None
|
Raises:
Type | Description |
---|---|
PydanticSerializationError
|
If serialization fails and no |
Returns:
Type | Description |
---|---|
Any
|
The serialized Python object. |