Data validation using Python type hints
Data validation using Python type hints.
Fast and extensible, Pydantic plays nicely with your linters/IDE/brain. Define how data should be in pure, canonical Python 3.7+; validate it with Pydantic.
We've started a company based on the principles that I believe have led to Pydantic's success. Learning more from the Company Announcement.
Pydantic V2 is a ground-up rewrite that offers many new features, performance improvements, and some breaking changes compared to Pydantic V1.
If you're using Pydantic V1 you may want to look at the
pydantic V1.10 Documentation or,
1.10.X-fixes git branch. Pydantic V2 also ships with the latest version of Pydantic V1 built in so that you can incrementally upgrade your code base and projects: from pydantic import v1 as pydantic_v1.
See documentation for more details.
Install using pip install -U pydantic or conda install pydantic -c conda-forge.
For more installation options to make Pydantic even faster,
see the Install section in the documentation.
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: Optional[datetime] = None
friends: List[int] = []
external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']}
user = User(**external_data)
print(user)
#> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
print(user.id)
#> 123
For guidance on setting up a development environment and how to make a contribution to Pydantic, see Contributing to Pydantic.
See our security policy.
pydantic-core to 2.14.5pydantic-core to 2.14.5ConfigDict.ser_json_inf_nan by @davidhewitt in #8159Literal from JSON keys when used as dict key by @sydney-runkle in pydantic/pydantic-core#1075custom_init on members of Union by @sydney-runkle in pydantic/pydantic-core#1076JsonValue bool serialization by @sydney-runkle in #8190Literal in Unions by @sydney-runkle in pydantic/pydantic-core#1089ValidateCallWrapper error when creating a model which has a @validate_call wrapped field annotation by @sydney-runkle in #8110The code released in v2.5.0 is functionally identical to that of v2.5.0b1.
pyright==1.1.335 by @Viicos in #8075ValidationError errors by @adriangb in #7806__doc__ argument in create_model() by @chris-spann in #7863regex_engine flag - meaning you can use with the Rust or Python regex libraries in constraints by @utkini in #7768ComputedFieldInfo by @alexmojaki in #7889ruff formatter by @Luca-Blight in #7930validation_error_cause to config by @zakstucke in #7626CallableDiscriminator and Tag by @dmontagu in #7983
examples and json_schema_extra to @computed_field by @alexmojaki in #8013JsonValue type by @dmontagu in #7998str as argument to Discriminator by @dmontagu in #8047SchemaSerializer.__reduce__ method to enable pickle serialization by @edoakes in pydantic/pydantic-core#1006ultra_strict with new smart union implementation, the way unions are validated has changed significantly to improve performance and correctness, we have worked hard to absolutely minimise the number of cases where behaviour has changed, see the PR for details - by @davidhewitt in pydantic/pydantic-core#867extra='allow' by @sydney-runkle in #7683Enum types with no cases by @sydney-runkle in #7927Generic before BaseModel by @alexmojaki in #7891jiter by @samuelcolvin in pydantic/pydantic-core#974__getattr__ for all package imports, improve import time by @samuelcolvin in #7947mypy issue with subclasses of RootModel by @sydney-runkle in #7677FieldInfo when a forward ref gets evaluated by @dmontagu in #7698SecretStr from JSON (regression in v2.4) by @sydney-runkle in #7729defer_build behavior with TypeAdapter by @sydney-runkle in #7736mypy versions by @dmontagu in #7742TypeVar handling when default is not set by @pmmmwh in #7719strict on Enum type fields by @sydney-runkle in #7761weakref.ref instead of subclassing to fix cloudpickle serialization by @edoakes in #7780model_post_init in subclasses by @alexmojaki in #7775json_schema_extra by @alexmojaki in #7803strict specification for UUID types by @sydney-runkle in #7865pydantic.Field(kw_only=True) with inherited dataclasses by @PrettyWood in #7827validate_call decorator for methods in classes with __slots__ by @sydney-runkle in #7883dataclasses.field default by @hramezani in #7898importlib_metadata on python 3.7 by @sydney-runkle in #7904| operator (Union) in PydanticRecursiveRef by @alexmojaki in #7892display_as_type for TypeAliasType in python 3.12 by @dmontagu in #7929NotRequired generics in TypedDict by @sydney-runkle in #7932TypeAliasType specifications produce different schema definitions by @alexdrydew in #7893PrivateAttr is passed from Annotated default position by @tabassco in #8004classmethod instead of classmethod[Any, Any, Any] by @Mr-Pepe in #7979Optional field with validate_default only performing one field validation by @sydney-runkle in pydantic/pydantic-core#1002definition-ref bug with Dict keys by @sydney-runkle in pydantic/pydantic-core#1014bool types with coerce_numbers_to_str=True by @sydney-runkle in pydantic/pydantic-core#1017NaN in float and decimal constraints by @davidhewitt in pydantic/pydantic-core#1037lax_str and lax_int support for enum values not inherited from str/int by @michaelhly in pydantic/pydantic-core#1015Union of List types by @sydney-runkle in pydantic/pydantic-core#1039max_digits and decimals to pass if normalized or non-normalized input is valid by @sydney-runkle in pydantic/pydantic-core#1049ValidationError messages by @Iipin in pydantic/pydantic-core#1050'-' as datetime input by @davidhewitt in pydantic/speedate#52 & pydantic/pydantic-core#1060pydanticpydantic-corePre-release, see the GitHub release for details.
models_json_schema for generic models by @adriangb in #7654Any by @adriangb in #7606Base64Url types by @dmontagu in #7286number to str coercion by @lig in #7508field_name and data in all validators if there is data and a field name by @samuelcolvin in #7542BaseModel.model_validate_strings and TypeAdapter.validate_strings by @hramezani in #7552plugins experimental implementation by @lig @samuelcolvin and @Kludex in #6820model_post_init in subclass with private attrs by @Viicos in #7302Extra as deprecated by @disrupted in #7299EncodedStr a dataclass by @Kludex in #7396annotated_handlers to be public by @samuelcolvin in #7569CoreSchema by @adriangb in #7523CoreSchema walking by @adriangb in #7528dict.get and dict.setdefault with more verbose versions in CoreSchema building hot paths by @adriangb in #7536CoreSchema discovery by @adriangb in #7535CoreSchema validation for faster startup times by @adriangb in #7565TypedDict from grandparent classes by @dmontagu in #7272strict config overridable in field for Path by @hramezani in #7281ser_json_<timedelta|bytes> on default in GenerateJsonSchema by @Kludex in #7269SkipValidation to referenced schemas by @adriangb in #7381__get_pydantic_core_schema__ signature by @hramezani in #7415TypeAdapter) by @sydney-runkle in #7435TypeError on model_validator in wrap mode by @pmmmwh in #7496repr work for instances that failed initialization when handling ValidationErrors by @dmontagu in #7439UUID values having UUID.version=None by @lig in #7566__iter__ returning private cached_property info by @sydney-runkle in #7570Field(..., exclude: bool) docs by @samuelcolvin in #7214Base64Str and Base64Bytes by @Kludex in #7192config.defer_build for serialization first cases by @samuelcolvin in #7024validators.md to correct validate_default kwarg by @lmmx in #7229tzinfo.fromutc method for TzInfo in pydantic-core by @lig in #7019__get_validators__ by @hramezani in #7197xfailing test for root model extra stop xfailing by @dmontagu in #6937Field.include by @hramezani in #6852Path fields by @samuelcolvin in #6903ForwardRef wrapper for py 3.10.0 (shim until bpo-45166) by @randomir in #6919main branch for badge links by @Viicos in #6925ser_json_bytes regarding base64 encoding by @Viicos in #7052@validate_call to work on async methods by @adriangb in #7046Settings and SettingsConfigDict by @JeanArhancet in #7002short_version and use it in links by @hramezani in #7115RootModel by @Kludex in #7113Field.exclude by @Viicos in #7086validate_assignment to use Field.frozen by @Viicos in #7103_core_utils by @samuelcolvin in #7040round_trip in Json type documentation by @jc-louis in #7137StringConstraints for use as Annotated metadata by @adriangb in #6605help(BaseModelSubclass) raises errors by @hramezani in #6758@model_validator(mode="after") by @ljodal in #6753contentSchema keyword for JSON schema by @dmontagu in #6715version_info() by @samuelcolvin in #6785SkipJsonSchema annotation by @Kludex in #6653GenericModel to MOVED_IN_V2 by @adriangb in #6776docs/usage/types/custom.md by @hramezani in #6803float -> Decimal coercion precision loss by @adriangb in #6810annotated_types.MaxLen validator for custom sequence types by @ImogenBits in #6809InstanceOf by @dmontagu in #6829json_encoders by @adriangb in #6811WeakValueDictionary to fix generic memory leak by @dmontagu in #6681config.defer_build to optionally make model building lazy by @samuelcolvin in #6823UUID serialization to pydantic-core by @davidhewitt in #6850json_encoders docs by @adriangb in #6848staticmethod/classmethod order with validate_call by @dmontagu in #6686Config by @samuelcolvin in #6847Field.exclude takes priority over call-time include/exclude by @hramezani in #6851GenerateSchema public by @adriangb in #6737Field.alias behavior in Pydantic V2 by @hramezani in #6508alias_priority by @tpdorsey in #6520pydantic-core to v2.2.0 by @lig in #6589enum error type docs by @lig in #6603max_length for unicode strings by @lig in #6559pydantic.v1 by @tpdorsey in #6604$ref as an alias by @dmontagu in #6568AnyUrl etc by @davidhewitt in #6618json_schema_extra on RootModel using Field by @lig in #6622transform docstring by @StefanBRas in #6649RootModel would change the value of __dict__, #6457 by @dmontaguconstr documentation, renamed old regex to new pattern, #6452 by @miiliGenerateJsonSchema.generate_definitions signature, #6436 by @dmontaguSee the full changelog here
First patch release of Pydantic V2
setattr (i.e. m.some_extra_field = 'extra_value')
are added to .model_extra if model_config extra='allowed'. Fixed #6333, #6365 by @aaraneySee the full changelog here
Pydantic V2 is here! :tada:
See this post for more details.
Third beta pre-release of Pydantic V2
See the full changelog here
Add from_attributes runtime flag to TypeAdapter.validate_python and BaseModel.model_validate.
See the full changelog here
First beta pre-release of Pydantic V2
See the full changelog here
Fourth pre-release of Pydantic V2
See the full changelog here
Third pre-release of Pydantic V2
See the full changelog here
Second pre-release of Pydantic V2
See the full changelog here
First pre-release of Pydantic V2!
See this post for more details.
... see here for earlier changes.