HISTORY.md
pydantic-core linker flags on macOS by @washingtoneg and @Viicos in #13147RootModel core metadata by @Viicos in #13129AttributeError subclasses with from_attributes by @Viicos in #13096ValidationInfo.field_name missing with model_validate_json() by @Viicos in #13084ValidationInfo.data missing with model_validate_json() by @davidhewitt in #13079The highlights of the v2.13 release are available in the blog post. Several minor changes (considered non-breaking changes according to our versioning policy) are also included in this release. Make sure to look into them before upgrading.
This release contains the updated pydantic.v1 namespace, matching version 1.10.26 which includes support for Python 3.14.
See the beta releases for all changes sinces 2.12.
Any when synthesizing _build_sources for BaseSettings.__init__() signature in the mypy plugin by @Viicos in #13049extra configuration by @Viicos in #13062ascii_only option to StringConstraints by @ai-man-codes in #12907exclude_if in computed fields by @andresliszt in #12748MISSING sentinel by @Viicos in #12908model_fields_set by @navalprakhar in #12817extras_schema when only extra_fields_behavior is set on the config in JSON Schema generation for typed dictionaries by @Viicos in #12810__pydantic_private__ is set in model_construct() with user-defined model_post_init() by @nightcityblade in #12816InstanceOf by @Viicos in #12705create_model() to be used as annotations in the Mypy plugin by @Br1an67 in #12879PlaceholderNode in Mypy plugin by @Viicos in #12929MISSING during model serialization with exclude_unset by @davidhewitt in #12905__init__() is called when using model_validate_strings() by @siewcapital in #12897validate_as() by @bledden in #12846UrlConstraints.__get_pydantic_core_schema__() by @bysiber in #12826This is the first beta release of the 2.13 version, mainly providing bug fixes and performance improvements for validation and serialization.
Notable changes include:
polymorphic_serialization option, solving issues with serialize_as_any introduced in 2.12.pydantic.v1 namespace. This version includes support for Python 3.14.pydantic-core repository was merged inside the main pydantic one.polymorphic_serialization option by @davidhewitt in #12518Literal root types as discriminator field types by @YassinNouh21 in #12680pydantic-core CI by @Viicos in #12752pydantic-core into pydantic by @davidhewitt in #12481complex() constructor unconditionally when validating complex Python data by @tanmaymunjal in #12498Decimal by @tanmaymunjal in #12500@field_serializer logic with @field_validator by @Viicos in #12577PydanticUserError a RuntimeError instead of a TypeError by @poliakovva in #12579root value when making root model shallow copies by @YassinNouh21 in #12679DecoratorInfos.build() implementation by @Viicos in #12536pydantic-core by @Viicos in #12549Literal validators by @davidhewitt in #12569LookupKey by @davidhewitt in #12571FieldInfo._copy() by @Viicos in #12727FieldInfo rebuilding when parameterizing generic models with an Annotated type by @Viicos in #12463InitVar being ignored when using with the pydantic.Field() function by @Viicos in #12495NamedTuple as values by @Viicos in #12506rebuild_dataclass() by @Viicos in #12513__pydantic_extra__ annotation handling by @Viicos in #12563MISSING sentinel is present in a nested model by @Viicos in #12635exclude_none is set by @davidhewitt in #12677field_definitions in create_model() by @lehmann-hqs in #12734kw_only with Field() by @jfadia in #12741typing.Union when replacing types under Python 3.14 by @Viicos in #12733pydantic-core by @dependabot[bot] in #12508This is the fifth 2.12 patch release, addressing an issue with the MISSING sentinel and providing several documentation improvements.
The next 2.13 minor release will be published in a couple weeks, and will include a new polymorphic serialization feature addressing the remaining unexpected changes to the serialize as any behavior.
model_construct() on a model with MISSING as a default value by @ornariece in #12522.This is the fourth 2.12 patch release, fixing more regressions, and reverting a change in the build() method
of the AnyUrl and Dsn types.
This patch release also fixes an issue with the serialization of IP address types, when serialize_as_any is used. The next patch release
will try to address the remaining issues with serialize as any behavior by introducing a new polymorphic serialization feature, that
should be used in most cases in place of serialize as any.
Fix issue with forward references in parent TypedDict classes by @Viicos in #12427.
This issue is only relevant on Python 3.14 and greater.
Exclude fields with exclude_if from JSON Schema required fields by @Viicos in #12430
Revert URL percent-encoding of credentials in the build() method
of the AnyUrl and Dsn types by @davidhewitt in
pydantic-core#1833.
This was initially considered as a bugfix, but caused regressions and as such was fully reverted. The next release will include an opt-in option to percent-encode components of the URL.
Add type inference for IP address types by @davidhewitt in pydantic-core#1868.
The 2.12 changes to the serialize_as_any behavior made it so that IP address types could not properly serialize to JSON.
Avoid getting default values from defaultdict by @davidhewitt in pydantic-core#1853.
This fixes a subtle regression in the validation behavior of the collections.defaultdict
type.
Fix issue with field serializers on nested typed dictionaries by @davidhewitt in pydantic-core#1879.
Add more pydantic-core builds for the three-threaded version of Python 3.14 by @davidhewitt in pydantic-core#1864.
This is the third 2.12 patch release, fixing issues related to the FieldInfo class, and reverting a change to the supported
after model validator function signatures.
FieldInfo.asdict() method, improve documentation around FieldInfo by @Viicos in #12411.
This also add back support for mutations on FieldInfo classes, that are reused as Annotated metadata. However, note that this is still
not a supported pattern. Instead, please refer to the added example in the documentation.The blog post section on changes was also updated to document the changes related to serialize_as_any.
pydantic-core version, as a corrupted CPython 3.10 manylinux2014_aarch64 wheel got uploaded (pydantic-core#1843).This is the first 2.12 patch release, addressing most (but not all yet) regressions from the initial 2.12.0 release.
None is converted as NoneType in Python 3.14 by @Viicos in #12370ValidationInfo for validation of default value by @Viicos in pydantic-core#1826MultiHostUrl builder by @willswire in pydantic-core#1829serialize_as_any serialization flag by @davidhewitt in pydantic-core#1829RootModel serialization issues by @davidhewitt in pydantic-core#1836This is the final 2.12 release. It features the work of 20 external contributors and provides useful new features, along with initial Python 3.14 support. Several minor changes (considered non-breaking changes according to our versioning policy) are also included in this release. Make sure to look into them before upgrading.
Note that Pydantic V1 is not compatible with Python 3.14 and greater.
See the beta releases for all changes sinces 2.11.
extra parameter to the validate functions by @anvilpete in #12233exclude_computed_fields serialization option by @Viicos in #12334preverse_empty_path URL options by @Viicos in #12336union_format parameter to JSON Schema generation by @Viicos in #12147__qualname__ parameter for create_model by @Atry in #12001TypeAdapter by @Viicos in #12324Any for context type annotation in TypeAdapter by @inducer in #12279FieldInfo in pydantic.fields.__all__ by @Viicos in #12339validation_alias in @validate_call by @Viicos in #12340Any as context annotation in plugin API by @Viicos in #12341stacklevel in warnings when possible by @Viicos in #12342This is the first beta release of the upcoming 2.12 release.
exclude_if at the field level by @andresliszt in #12141ValidateAs annotation helper by @Viicos in #11942pydantic-core version is installed by @Viicos in #12196__getattr__() behavior on Pydantic models when a property raised an AttributeError and extra values are present by @raspuchin in #12106validate_assignment set by @Viicos in #12173ImportString JSON serialization for objects with a name attribute by @chr1sj0nes in #12219pydantic-core to v2.40.1 by @Viicos in #12314This is the first alpha release of the upcoming 2.12 release, which adds initial support for Python 3.14.
__pydantic_on_complete__() hook that is called once model is fully ready to be used by @DouweM in #11762Decimal type by @Dima-Bulavenko in #11987doc attribute on dataclass fields by @Viicos in #12077MISSING sentinel by @Viicos in #11883create_model() by @Viicos in #11714GenerateSchema class by @Viicos in #11733inspect.getsourcelines() for docstring extraction on Python 3.13 and greater by @Viicos in #11829FieldInfo creation implementation by @Viicos in #11898Secret covariant by @bluenote10 in #12008field_name in validator core schemas by @DouweM in #11761validate_assignment can be unpickled by @Viicos in #11769function-before schemas during schema gathering by @Viicos in #11801FieldInfo is complete after applying type variable map by @Viicos in #11855model_rebuild() by @Viicos in #11890FieldInfo by @Viicos in #11946SkipValidation by @ygsh0816 in #12002Field() default with validate_default set to True by @Viicos in #11988Field() function in dataclasses by @Viicos in #12051mkdocs-llmstxt to v0.2.0 by @Viicos in #11725pydantic-core to v2.35.1 by @Viicos in #11963FieldInfo instance if necessary during FieldInfo build by @Viicos in #11898FieldInfo by @Viicos in #11946FieldInfo is complete after applying type variable map by @Viicos in #11855model_rebuild() by @Viicos in #11890create_model() by @Viicos in #11714.
This change was backported as it was previously possible (although not meant to be supported)
to provide model_config as a field, which would make it possible to provide both configuration
and bases.function-before schemas during schema gathering by @Viicos in #11801mkdocs-llmstxt to v0.2.0 by @Viicos in #11725pydantic-core to v2.33.1 by @Viicos in #11678__pydantic_private__ exists before setting private attributes by @Viicos in #11666FieldInfo._complete when using field from parent class by @Viicos in #11668'definitions-ref' schemas containing serialization schemas or metadata by @Viicos in #11644Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general). See the blog post for more details.
encoded_string() method to the URL types by @YassinNouh21 in #11580defer_build with @validate_call decorator by @Viicos in #11584@with_config decorator to be used with keyword arguments by @Viicos in #11608generate_arguments_schema() function by @Viicos in #11572pydantic-core to v2.33.0 by @Viicos in #11631NotRequired qualifier not taken into account in stringified annotation by @Viicos in #11559pydantic-core to v2.32.0 by @Viicos in #11567default_factory_takes_validated_data property to FieldInfo by @Viicos in https://github.com/pydantic/pydantic/pull/11034type[] by @Viicos in https://github.com/pydantic/pydantic/pull/11088create_model field definitions format by @Viicos in https://github.com/pydantic/pydantic/pull/11032model_fields and model_computed_fields on instances by @Viicos in https://github.com/pydantic/pydantic/pull/11169GenerateSchema class by @sydney-runkle in https://github.com/pydantic/pydantic/pull/10846get_type_ref by @Viicos in https://github.com/pydantic/pydantic/pull/10863pydantic-core core schema validation by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11271FieldInfo annotations if required during schema building by @Viicos in https://github.com/pydantic/pydantic/pull/10769__setattr__ performance of Pydantic models by caching setter functions by @MarkusSintonen in https://github.com/pydantic/pydantic/pull/10868_typing_extra module by @Viicos in https://github.com/pydantic/pydantic/pull/11255CoreConfig instance by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11384pydantic-core and thus use SchemaValidator and SchemaSerializer caching by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11402TypeAdapter instance repr by @sydney-runkle in https://github.com/pydantic/pydantic/pull/10872TypeAdapter by @Viicos in https://github.com/pydantic/pydantic/pull/10893Literal values if using PEP 695 type aliases by @Viicos in https://github.com/pydantic/pydantic/pull/11114__subclasscheck__ on ModelMetaclass to avoid memory leak and performance issues by @Viicos in https://github.com/pydantic/pydantic/pull/11116_extract_get_pydantic_json_schema() parameter by @Viicos in https://github.com/pydantic/pydantic/pull/11155Annotated form by @Viicos in https://github.com/pydantic/pydantic/pull/11109deprecated_instance_property warning by @Viicos in https://github.com/pydantic/pydantic/pull/11200WithJsonSchema schema to avoid sharing mutated data by @thejcannon in https://github.com/pydantic/pydantic/pull/11014CoreMetadata definition by @Viicos in https://github.com/pydantic/pydantic/pull/11216_Definitions class by @Viicos in https://github.com/pydantic/pydantic/pull/11208root type in the mypy plugin by @Viicos in https://github.com/pydantic/pydantic/pull/11212use_attribute_docstrings by @Viicos in https://github.com/pydantic/pydantic/pull/11246decimal_places_validator by @misrasaurabh1 in https://github.com/pydantic/pydantic/pull/11281validation_alias in the mypy plugin by @Viicos in https://github.com/pydantic/pydantic/pull/11295"examples" keys by @Viicos in https://github.com/pydantic/pydantic/pull/11305GenerateJsonSchema.literal_schema() implementation by @misrasaurabh1 in https://github.com/pydantic/pydantic/pull/11321ClickHouseDsn by @Maze21127 in https://github.com/pydantic/pydantic/pull/11319Decimal instances by @Viicos in https://github.com/pydantic/pydantic/pull/11350additionalProperties: True for arbitrary dictionary schemas by @austinyu in https://github.com/pydantic/pydantic/pull/11392fallback parameter in serialization methods by @Viicos in https://github.com/pydantic/pydantic/pull/11398Sequence types by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11435__get_validators__ on classes where __get_pydantic_core_schema__ is also defined by @tlambert03 in https://github.com/pydantic/pydantic/pull/11444validate_by_name to True when validate_by_alias is False by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11503Any when synthesizing BaseSettings.__init__ signature in the mypy plugin by @Viicos in https://github.com/pydantic/pydantic/pull/11497ValueError on year zero by @davidhewitt in https://github.com/pydantic/pydantic-core/pull/1583dataclass InitVar shouldn't be required on serialization by @sydney-runkle in https://github.com/pydantic/pydantic-core/pull/1602check_pydantic_core_version() function by @Viicos in https://github.com/pydantic/pydantic/pull/11324greenlet development dependency by @Viicos in https://github.com/pydantic/pydantic/pull/11351typing-inspection library by @Viicos in https://github.com/pydantic/pydantic/pull/11479pydantic-core to v2.31.1 by @sydney-runkle in https://github.com/pydantic/pydantic/pull/11526Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general). This is another early alpha release, meant to collect early feedback from users having issues with core schema builds.
CoreConfig instance by @sydney-runkle in #11384examples keys by @Viicos in #11366additionalProperties: True for arbitrary dictionary schemas by @austinyu in #11392fallback parameter in serialization methods by @Viicos in #11398ruff from 0.9.2 to 0.9.5 by @Viicos in #11407pydantic-core to v2.29.0 by @mikeedjones in #11402Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general). This is an early alpha release, meant to collect early feedback from users having issues with core schema builds.
default_factory_takes_validated_data property to FieldInfo by @Viicos in #11034type[] by @Viicos in #11088create_model field definitions format by @Viicos in #11032model_fields and model_computed_fields on instances by @Viicos in #11169GenerateSchema class by @sydney-runkle in #10846deque schema gen to GenerateSchema class by @sydney-runkle in #11239Mapping schema gen to GenerateSchema to complete removal of prepare_annotations_for_known_type workaround by @sydney-runkle in #11247pydantic-core core schema validation by @sydney-runkle in #11271FieldInfo annotations if required during schema building by @Viicos in #10769get_type_ref by @Viicos in #10863__setattr__ performance of Pydantic models by caching setter functions by @MarkusSintonen in #10868_typing_extra module by @Viicos in #11255_internal/_validators.py by @tkasuz in #10763TypeAdapter instance repr by @sydney-runkle in #10872Literal values if using PEP 695 type aliases by @Viicos in #11114__subclasscheck__ on ModelMetaclass to avoid memory leak and performance issues by @Viicos in #11116_extract_get_pydantic_json_schema() parameter by @Viicos in #11155Annotated form by @Viicos in #11109openapi-python-client check in issue creation for third-party failures, use main branch by @sydney-runkle in #11182deprecated_instance_property warning by @Viicos in #11200WithJsonSchema schema to avoid sharing mutated data by @thejcannon in #11014CoreMetadata definition by @Viicos in #11216_Definitions class by @Viicos in #11208root type in the mypy plugin by @Viicos in #11212use_attribute_docstrings by @Viicos in #11246decimal_places_validator by @misrasaurabh1 in #11281validation_alias in the mypy plugin by @Viicos in #11295GenerateJsonSchema.literal_schema() implementation by @misrasaurabh1 in #11321ClickHouseDsn by @Maze21127 in #11319Decimal instances by @Viicos in #11350ValueError on year zero by @davidhewitt in pydantic-core#1583ruff to v0.9.0 by @sydney-runkle in #11254uv.lock deps update by @sydney-runkle in #11333check_pydantic_core_version() function by @Viicos in #11324greenlet development dependency by @Viicos in #11351pydantic-core to v2.28.0 by @Viicos in #11364'examples' keys by @Viicos in #11325AnyUrl objects by @alexprabhat99 in #11082len to _BaseUrl to avoid TypeError by @Kharianne in #11111pydantic-core to v2.27.2 by @davidhewitt in #11138defer_build is set on Pydantic dataclasses by @Viicos in #10984dict core schema keys by @Viicos in #10989PlainSerializer and WrapSerializer functions by @Viicos in #11008default_factory_takes_validated_data property to FieldInfo by @Viicos in #11034serialization mode by @sydney-runkle in #11035Secret types and Url types by @sydney-runkle in #10947Field.default to be compatible with Python 3.8 and 3.9 by @Viicos in #10972BaseModel.__replace__ definition from type checkers by @Viicos in #10979TypeAdapter by @Viicos in #10893default_factory utils by @sydney-runkle in #10909model_fields and model_computed_fields by @sydney-runkle in #10911dataclasses by @sydney-runkle in #10928globals of the function when evaluating the return type of serializers and computed_fields by @Viicos in #10929'' by @sydney-runkle in #10936python mode serialization for complex inference by @sydney-runkle in pydantic-core#1549pydantic-core version to v2.27.1 by @sydney-runkle in #10938The code released in v2.10.0 is practically identical to that of v2.10.0b2.
See the v2.10 release blog post for the highlights!
fractions.Fraction by @sydney-runkle in #10318Hashable for json validation by @sydney-runkle in #10324SocketPath type for linux systems by @theunkn0wn1 in #10378examples by @sydney-runkle in #10417defer_build for Pydantic dataclasses by @Viicos in #10313TypedDict to type hint variadic keyword arguments with @validate_call by @Viicos in #10416protected_namespaces by @sydney-runkle in #10522propertyNames in JSON schema by @FlorianSW in #10478__replace__ protocol for Python 3.13+ support by @sydney-runkle in #10596sort method for JSON schema generation by @sydney-runkle in #10595@validate_call callable argument by @kc0506 in #10627experimental_allow_partial support by @samuelcolvin in #10748ValidationError and PydanticCustomError by @Youssefares in pydantic/pydantic-core#1413trailing-strings support to experimental_allow_partial by @sydney-runkle in #10825rebuild() method for TypeAdapter and simplify defer_build patterns by @sydney-runkle in #10537TypeAdapter instance repr by @sydney-runkle in #10872SchemaGenerator until interface is more stable by @sydney-runkle in #10303defer_build on TypeAdapters, removing experimental flag by @sydney-runkle in #10329mro of generic subclass by @kc0506 in #10100b64decode and b64encode for Base64Bytes type by @sydney-runkle in #10486@dataclass decorator and with the __pydantic_config__ attribute by @sydney-runkle in #10406Ellipsis (...) with Field by @Viicos in #10661Literals and Enums by @Viicos in #10692Any or Never when replacing type variables by @Viicos in #10338base64 bytes by @bschoenmaeckers in pydantic/pydantic-core#1448CoreMetadata refactor with an emphasis on documentation, schema build time performance, and reducing complexity by @sydney-runkle in #10675pydantic-core to v2.27.0 by @sydney-runkle in #10825computed_field with field_serializer by @nix010 in #10390Predicate issue in v2.9.0 by @sydney-runkle in #10321annotated-types bound by @sydney-runkle in #10327tzdata install requirement into optional timezone dependency by @jakob-keller in #10331namedtuple core schemas by @Viicos in #10337IncEx type alias definition by @Viicos in #10339ModelMetaclass.mro by @Viicos in #10372computed_fields by @Viicos in #10391inspect.iscoroutinefunction works on coroutines decorated with @validate_call by @MovisLi in #10374NameError when using validate_call with PEP 695 on a class by @kc0506 in #10380ZoneInfo with various invalid types by @sydney-runkle in #10408PydanticUserError on empty model_config with annotations by @cdwilson in #10412_IncEx type alias, only allow True by @Viicos in #10414PlainValidator by @Viicos in #10427json_schema_input_type by @Viicos in #10439Representation by @Viicos in #10480max_digits and decimal_places) by @sydney-runkle in #10506__pydantic_core_schema__ from the current class during schema generation by @Viicos in #10518stacklevel on deprecation warnings for BaseModel by @sydney-runkle in #10520stacklevel in BaseModel.__init__ by @Viicos in #10526ConfigWrapper.core_config to take the title directly by @Viicos in #10562mode='python' by @sydney-runkle in #10594Base64Etc types by @sydney-runkle in #10584validate_call ignoring Field in Annotated by @kc0506 in #10610Self is invalid by @kc0506 in #10609core_schema.InvalidSchema instead of metadata injection + checks by @sydney-runkle in #10523type with typing.Self and type aliases by @kc0506 in #10621Field and PrivateAttr functions by @Viicos in #10651mypy plugin implementation by @Viicos in #10669typing_extensions variant of TypeAliasType by @Daraan in #10713BaseModel.model_copy() by @Viicos in #10751isinstance behavior for urls by @sydney-runkle in #10766cached_property can be set on Pydantic models by @Viicos in #10774host_required for URLs by @Viicos in pydantic/pydantic-core#1488coerce_numbers_to_str enabled and string has invalid Unicode character by @andrey-berenda in pydantic/pydantic-core#1515complex values in Enums by @changhc in pydantic/pydantic-core#1524_typing_extra module by @Viicos in #10725bytearray to TypeAdapter.validate_json signature by @samuelcolvin in #10802Field by @Viicos in #10816validate_call by @sydney-runkle in #10807IncEx type alias to be compatible with mypy by @Viicos in #10813__signature__ a lazy property, do not deepcopy defaults by @Viicos in #10818__signature__ lazy for dataclasses, too by @sydney-runkle in #10832AnyUrl to preserve behavior from v2.9 by @sydney-runkle in #10856Pre-release, see the GitHub release for details.
Pre-release, see the GitHub release for details.
<!-- package description limit -->Callable discriminators by @sydney-runkle in #10400PlainValidator by @Viicos in #10427Union serialization warnings by @sydney-runkle in pydantic/pydantic-core#1449_IncEx type alias, only allow True by @Viicos in #10414ZoneInfo validation with various invalid types by @sydney-runkle in #10408annotated-types bound to >=0.6.0 by @sydney-runkle in #10327tzdata install requirement into optional timezone dependency by @jakob-keller in #10331IncExc type alias definition by @Viicos in #10339The code released in v2.9.0 is practically identical to that of v2.9.0b2.
ZoneInfo by @Youssefares in #9896Config.val_json_bytes by @josh-newman in #9770complex number by @changhc in #9654annotated_types.Not by @aditkumar72 in #10210WithJsonSchema to inject $refs w/ http or https links by @dAIsySHEng1 in #9863PathLike types by @nix010 in #9764str or callable discriminators to select the correct serializer by @sydney-runkle in in pydantic/pydantic-core#1397dict type json_schema_extra by @sydney-runkle in #9792
pattern for incompatible types by @sydney-runkle in #10158'allOf' JSON schema workarounds by @dpeachey in #10029typed_dict_cls data from CoreMetadata by @sydney-runkle in #10180Examples class by @Viicos in #10181initial_metadata from internal metadata construct by @sydney-runkle in #10194re.Pattern.search instead of re.Pattern.match for consistency with rust behavior by @tinez in pydantic/pydantic-core#1368pydantic-core serialization warning by @BoxyUwU in pydantic/pydantic-core#1377pydantic-core, change metadata type hint in core schemas from Any -> Dict[str, Any] | None by @sydney-runkle in pydantic/pydantic-core#1411self isn't returned from model validator by @sydney-runkle in #10255BaseModel by @sydney-runkle in #10013multiple_of_validator() by 31% in pydantic/_internal/_validators.py by @misrasaurabh1 in #9839ModelPrivateAttr.__set_name__() by 18% in pydantic/fields.py by @misrasaurabh1 in #9841dataclass() by 7% in pydantic/dataclasses.py by @misrasaurabh1 in #9843_field_name_for_signature by 37% in pydantic/_internal/_signature.py by @misrasaurabh1 in #9951GenerateSchema._unpack_refs_defs by 26% in pydantic/_internal/_generate_schema.py by @misrasaurabh1 in #9949apply_each_item_validators by 100% in pydantic/_internal/_generate_schema.py by @misrasaurabh1 in #9950ConfigWrapper.core_config by 28% in pydantic/_internal/_config.py by @misrasaurabh1 in #9953use_enum_values on Literal types by @kwint in #9787BaseModel/RootModel inheritance by @dmontagu in #9913str type annotation with Any in validator factories in documentation on validators by @maximilianfellhuber in #9885ComputedFieldInfo.wrapped_property pointer when a property setter is assigned by @tlambert03 in #9892main.IncEnx by @tlambert03 in #9924type[Annotated[...]] by @Viicos in #9932mypy plugin: handle frozen fields on a per-field basis by @dmontagu in #9935invalid-annotated-type error code by @sydney-runkle in #9948uuid, url, and ip types by @sydney-runkle in #9975date schemas to _generate_schema.py by @sydney-runkle in #9976decimal.Decimal validation to _generate_schema.py by @sydney-runkle in #9977_std_types_schema.py by @sydney-runkle in #9959GenerateSchema.match_type options by @sydney-runkle in #9961dataclass ignoring default_factory passed in Annotated by @kc0506 in #9971Sequence ignoring discriminator by @kc0506 in #9980IPvAnyAddress and IPvAnyInterface by @haoyun in #9990mypy plugin for from_orm check requiring from_attributes=True config by @radekwlsk in #9938strict=True to __init__ in mypy plugin by @kc0506 in #9998deque annotations by @sydney-runkle in #10018__pydantic_extra__ annotation in specific circumstances by @Viicos in #10070frozen enforcement for dataclasses by @sydney-runkle in #10066__get_pydantic_core_schema__ signature by @Viicos in #10075is_annotated consistently by @Viicos in #10095PydanticDeprecatedSince26 typo by @kc0506 in #10101pyright tests, refactor model decorators signatures by @Viicos in #10092ip serialization logic by @sydney-runkle in #10112dataclasses by @mochi22 in #10082when_used set to 'json-unless-none' and the default value is None by @Viicos in #10121ImportString special cases by @sydney-runkle in #10137__ prefixed annotations by @sydney-runkle in #10136nullable schemas with serialization schema available during JSON Schema generation by @Viicos in #10132BaseModel annotations by @kc0506 in #10110PrivateAttr with Annotated by @Viicos in #10157number type for literal and enum schemas by @Viicos in #10172Mapping and MutableMapping annotations to use mapping schema instead of dict schema by @sydney-runkle in #10020field_serializer with computed field when using * by @nix010 in pydantic/pydantic-core#1349Union serializer before inference by @sydney-runkle in pydantic/pydantic-core#1398float serialization behavior in strict mode by @sydney-runkle in pydantic/pydantic-core#1400exactness into Decimal validation logic to improve union validation behavior by @sydney-runkle in in pydantic/pydantic-core#1405pytest.warns() by @mgorny in #10241ModelMetaclass by @Viicos in #10242__init__ by @Viicos in #10264BigInt serialization for int subclasses by @kxx317 in pydantic/pydantic-core#1417info by @sydney-runkle in #10277__pydantic_complete__ is set when rebuilding dataclasses by @Viicos in #10291schema_generator config value in TypeAdapter by @sydney-runkle in #10300ruff to v0.5.0 and pyright to v1.1.369 by @sydney-runkle in #9801pydantic-extra-types to v2.9.0 by @sydney-runkle in #9832pdm v2.18.1 by @Viicos in #10138v1 version stub to v1.10.18 by @sydney-runkle in #10214pydantic-core to v2.23.2 by @sydney-runkle in #10311pydanticpydantic-corePre-release, see the GitHub release for details.
Pre-release, see the GitHub release for details.
ruff to v0.5.0 and pyright to v1.1.369 by @sydney-runkle in #9801pydantic-core to v2.20.1, pydantic-extra-types to v2.9.0 by @sydney-runkle in #9832to_snake from v2.7 -> v2.8 by @sydney-runkle in #9812The code released in v2.8.0 is functionally identical to that of v2.8.0b1.
v1.1.367 and add type checking tests for pipeline API by @adriangb in #9674pydantic.v1 stub to v1.10.17 by @sydney-runkle in #9707v2.8.0b1 by @sydney-runkle in #9741pydantic-core to v2.20.0 by @sydney-runkle in #9745pdm version used for pdm.lock to v2.16.1 by @sydney-runkle in #9761ruff v0.4.8 by @Viicos in #9585defer_build for TypeAdapter by @MarkusSintonen in #8939deprecated field in json schema by @NeevCohen in #9298fail_fast feature by @uriyyo in #9708ser_json_inf_nan='strings' mode to produce valid JSON by @josh-newman in pydantic/pydantic-core#1307Annotated field by @nix010 in #9170__validators__ values in create_model by @sydney-runkle in #9697smart union matching logic by @sydney-runkle in pydantic/pydantic-core#1322
You can read more about our smart union matching logic here. In some cases, if the old behavior
is desired, you can switch to left-to-right mode and change the order of your Union members._display_error_loc() by 25% in pydantic/v1/error_wrappers.py by @misrasaurabh1 in #9653_get_all_json_refs() by 34% in pydantic/json_schema.py by @misrasaurabh1 in #9650is_pydantic_dataclass() by 41% in pydantic/dataclasses.py by @misrasaurabh1 in #9652to_snake() by 27% in pydantic/alias_generators.py by @misrasaurabh1 in #9747unwrap_wrapped_function() by 93% in pydantic/_internal/_decorators.py by @misrasaurabh1 in #9727__spec__.parent with __package__ by @hramezani in #9331Sequence type by @anesmemisevic in #9303_frame_depth by @Viicos in #9353ImportString json schema compatible by @amitschang in #9344PrivateAttr) from __init__ signature in type checkers by @idan22moral in #9293TypeVar defaults robust to the CPython PEP-696 implementation by @AlexWaygood in #9426PlainSerializer with builtin types by @Viicos in #9450strict specification for StringConstraint(strict=False) by @vbmendes in #9476Self where possible by @Viicos in #9479RootModel.model_construct signature in the mypy plugin by @Viicos in #9480validation_context by @OhioDschungel6 in #9508dump_json/dump_python by @alexcouper in #9495Field() constructor by @bjmc in #9484TypeAdapter by @Viicos in #9570__setstate__ of BaseModel by @anhpham1509 in #9584PEP 746 by @adriangb in #9587TypeVar fields by @dmontagu in #9606regex flags in validation and json schema by @sydney-runkle in #9591IpvAnyAddress by @sydney-runkle in #9640__pydantic_extra__ by @dmontagu in #9659Optional[Decimal] by @lazyhope in #9754validate_call type params fix by @sydney-runkle in #9760re.Pattern object in regex patterns to allow for regex flags by @sydney-runkle in pydantic/pydantic-core#1318Pre-release, see the GitHub release for details.
pydantic.v1 to v1.10.16 reference by @sydney-runkle in #9639recursive_guard as kwarg in FutureRef._evaluate by @vfazio in #9612pydantic-core to v2.18.4 by @sydney-runkle in #9550pydantic-core to v2.18.3 by @sydney-runkle in #9515__spec__.parent with __package__ by @hramezani in #9331ints with leading unary minus by @RajatRajdeep in pydantic/pydantic-core#1291str subclass validation for enums by @sydney-runkle in pydantic/pydantic-core#1273BigInts in Literals and Enums by @samuelcolvin in pydantic/pydantic-core#1297str subclass as input by @davidhewitt in pydantic/pydantic-core#1296pydantic-core to v2.18.2 by @sydney-runkle in #9307… by @LouisGobert in #9214validation_alias behavior with model_construct for AliasChoices and AliasPath by @sydney-runkle in #9223typing.Literal and import it outside the TYPE_CHECKING block by @frost-nzcr4 in #9232Secret serialization schema, applicable for unions by @sydney-runkle in #9240strict application to function-after with use_enum_values by @sydney-runkle in #9279model_construct on a class which defines model_post_init fails with AttributeError by @babygrimes in #9168model_json_schema with config types by @NeevCohen in #9287int by @samuelcolvin in pydantic/pydantic-core#1269ints with leading unary plus by @cknv in pydantic/pydantic-core#1272extra != 'ignore' and from_attributes=True by @davidhewitt in pydantic/pydantic-core#1276Enum's missing function as ValidationError by @sydney-runkle in pydantic/pydantic-core#1274Iterable validation by @davidhewitt in pydantic/pydantic-core#1271The code released in v2.7.0 is practically identical to that of v2.7.0b1.
pyproject.toml sections by @Viicos in #8899pydantic-core to v2.18.1 by @sydney-runkle in #9211jiter v0.2.0 by @samuelcolvin in pydantic/pydantic-core#1250FieldInfo.description by @Viicos in #6563with_config decorator to comply with typing spec by @Viicos in #8611ByteSize.human_readable by @jks15satoshi in #8706Secret base type by @conradogarciaberrotaran in #8519Sphinx inventories for cross references in docs by @Viicos in #8682deprecated fields by @Viicos in #8237field_serializer('*') by @ornariece in #9001model_config is defined as a model property by @alexeyt101 in #9004create_model() to support typing.Annotated as input by @wannieman98 in #8947ClickhouseDsn support by @solidguy7 in #9062re.Pattern[str] to pattern field by @jag-k in #9053serialize_as_any runtime setting by @sydney-runkle in #8830typing.Self by @Youssefares in #9023context to serialization by @ornariece in #8965Finalized in v2.7.0, rather than v2.7.0b1:
warnings parameter for serialization utilities to allow raising a warning by @Lance-Drane in #9166model_construct behavior with extra by @sydney-runkle in #8807RootModel subclasses by @sydney-runkle in #8857PEP570 syntax by @Viicos in #8940enum and type to the JSON schema for single item literals by @dmontagu in #8944update_json_schema internal function by @sydney-runkle in #9125enum validator improvements by @samuelcolvin in #9045enum validation and serialization to Rust by @samuelcolvin in #9064aarch64(Note: SIMD on x86 will be implemented in a future release) by @samuelcolvin in in pydantic/jiter#65Cow<str> from jiter by @davidhewitt in pydantic/pydantic-core#1231Sequences by @sydney-runkle in #8614__qualname__ by @anci3ntr0ck in #8642__pydantic_extra__ annotation being a string or inherited by @alexmojaki in #8659NameEmail by @Holi0317 in #8650BaseModel by @bluenote10 in #8651mypy plugin and no_strict_optional = True by @dmontagu in #8666ByteSize error type change by @sydney-runkle in #8681__pydantic_config__ ignored for TypeDict by @13sin in #8734pytest v8.0.0 due to pytest.warns() starting to work inside pytest.raises() by @mgorny in #8678is_valid_field from 1.x for mypy plugin by @DanielNoord in #8738mypy strict equality flag by @dmontagu in #8799FieldInfo.__repr_args__ by @sydney-runkle in #8801BaseModel type annotations to be resolvable by typing.get_type_hints by @devmonkey22 in #7680AliasGenerator by @sydney-runkle in #8810date -> datetime timezone assumption fix by @sydney-runkle in #8823ast.Str by @Viicos in #8837deprecated decorators by @Viicos in #8877NameEmail if name includes an email address by @NeevCohen in #8860TypeAdapter's typing compatible with special forms by @adriangb in #8923enums by @dmontagu in #8920model_json_schema usage by @sydney-runkle in #8928mypy plugin by @dmontagu in #9008PlainSerializer usage with std type constructor by @sydney-runkle in #9031Model.__getattr__() by @NeevCohen in #9082ClassVar forward ref inherited from parent class by @alexmojaki in #9097True by @andresliszt in #8977deque when passed to Sequence[blah blah blah] by @sydney-runkle in #9128model_post_init by @Viicos in #9134model_construct with validation_alias by @ornariece in #9144Literal null types by @bruno-f-cruz in #9135Pre-release, see the GitHub release for details.
AliasGenerator with computed_field decorator by @sydney-runkle in #8806pydantic-settings version in the docs by @hramezani in #8906pydantic-core 2.16.3 by @sydney-runkle in #8879pydantic-core 2.16.2 by @sydney-runkle in #8717mypy plugin and no_strict_optional = True by @dmontagu in #8666ByteSize error type change by @sydney-runkle in #8681Field annotations in dataclasses by @sydney-runkle in #8679PlainValidator by @sydney-runkle in #8710Union by @davidhewitt in pydantic/pydantic-core#1174computed_field JSON serializer exclude_none behavior by @sydney-runkle in pydantic/pydantic-core#1187The code released in v2.6.0 is practically identical to that of v2.6.0b1.
email-validator version >= 2.0 by @commonism in #6033pydantic-extra-types==2.4.1 by @yezz123 in #8478pyright==1.1.345 by @Viicos in #8453NatsDsn by @ekeew in #6874ConfigDict.ser_json_inf_nan by @davidhewitt in #8159types.OnErrorOmit by @adriangb in #8222AliasGenerator usage by @sydney-runkle in #8282yyyy-MM-DD datetime parsing by @sydney-runkle in #8404ByteSize class #8415 by @luca-matei in #8507ByteSize by @geospackle in #8537eval_type_backport to handle union operator and builtin generic subscripting in older Pythons by @alexmojaki in #8209dataclass fields init by @dmontagu in #8552ValidationError by @davidhewitt in pydantic/pydantic-core#1119self in BaseModel constructor, so no field name can ever conflict with it by @ariebovenberg in #8072@validate_call return a function instead of a custom descriptor - fixes binding issue with inheritance and adds self/cls argument to validation errors by @alexmojaki in #8268BaseModel docstring from JSON schema description by @sydney-runkle in #8352classproperty decorator for model_computed_fields by @Jocelyn-Gas in #8437int extraction by @samuelcolvin in pydantic/pydantic-core#1155dataclass serialization speedups by @samuelcolvin in pydantic/pydantic-core#1162HashMap creation when looking up small JSON objects in LazyIndexMaps by @samuelcolvin in pydantic/jiter#55Peak with more efficient Peek by @davidhewitt in pydantic/jiter#48getattr warning in deprecated BaseConfig by @tlambert03 in #7183model_fields, not whole __dict__ by @alexmojaki in #7786mypy plugin by @dmontagu in #7411mypy error on untyped ClassVar by @vincent-hachin-wmx in #8138BaseModel.__eq__ instead of whole __dict__ by @QuentinSoubeyranAqemia in #7825strict docstring in model_validate method. by @LukeTonin in #8223computed_field by @Viicos in #8227validate_call decorator to be dynamically assigned to a class method by @jusexton in #8249unittest.mock deprecation warnings by @ibleedicare in #8262JsonValue contains subclassed primitive values by @jusexton in #8286mypy error on free before validator (classmethod) by @sydney-runkle in #8285to_snake conversion by @jevins09 in #8316ModelMetaclass.__prepare__ by @slanzmich in #8305config specification when initializing a TypeAdapter when the annotated type has config already by @sydney-runkle in #8365alias in dataclass signature by @NeevCohen in #8387Field(...) in a forward ref by @dmontagu in #8494__dict__ with model_construct call by @sydney-runkle in #8500path_type creation when globals does not contain __name__ by @hramezani in #8470from __future__ import annotations by @sydney-runkle in #8513@deprecated by @Viicos in #8294model_construct call by @sydney-runkle in #8525TypeAliasType for types with refs by @dmontagu in #8526pydantic.Field(repr=False) in dataclasses by @tigeryy2 in #8511dataclass_transform behavior for RootModel by @Viicos in #8163exclude_none for json serialization of computed_fields by @sydney-runkle in pydantic/pydantic-core#1098pydanticpydantic-corePre-release, see the GitHub release for details.
pydantic-core to 2.14.6pydantic-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
CallableDiscriminator renamed to Discriminator by @dmontagu in #8047examples 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.
typing-extensions by @Viicos in https://github.com/pydantic/pydantic/pull/11764This release provides proper support for Python 3.13, with (Cythonized) wheels published for this version.
As a consequence, Cython was updated from 0.29.x to 3.0.x.
3.0.x.pyproject.toml, make use of PEP 517 build options.build instead of direct setup.py invocations.isinstance check by @alicederyn in https://github.com/pydantic/pydantic/pull/10645to_lower_camel to __all__ in utils.py by @sydney-runkle (direct commit)mypy v1 plugin for mypy 1.11 release by @flaeppe in https://github.com/pydantic/pydantic/pull/10139.schema(by_alias=False) by @exs-dwoodward in https://github.com/pydantic/pydantic/pull/10146v1 namespace to fix typing and object resolution in python>3.11 by @exs-dwoodward in https://github.com/pydantic/pydantic/pull/9660pydantic.validate_email, #7673 by @hramezanimaxlen property being dropped on deque validation. Happened only if the deque item has been typed. Changes the _validate_sequence_like func, #6581 by @maciekglowkaJson field support to settings management, #6250 by @hramezaniLiteral usage with typing-extension==4.6.0, #5826 by @hramezaniAnyClassMethod for changes in python/typeshed#9771, #5505 by @ITProKyleConstrainedStr with regex as dict key, #5223 by @matejetzfrom_orm in their own classes, #5187 by @dmontaguInitVar usage with pydantic dataclasses, mypy version 1.1.1 and the custom mypy plugin, #5162 by @cdce8pfunctools.partial and functools.partialmethod when checking the signature, #5126 by @JensHeinrichdataclass_transform decorator for pydantic dataclasses, #5111 by @cdce8pValidationError, not ConfigError, when a discriminator value is unhashable, #4773 by @kurtmckeeGenericModels with complex sets of models, #5052 by @MarkusSintonenRecursionError when deep-copying dataclass types wrapped by pydantic, #4949 by @mbillingrX | Y union syntax breaking GenericModel, #4146 by @thenxtyping-extensions>=4.2.0, #4885 by @samuelcolvinNOTE: v1.10.3 was "yanked" from PyPI due to #4885 which is fixed in v1.10.4
schema and schema_json on models where a model instance is a one of default values, #4781 by @BobroniumDataclassProxy, #4695 by @PrettyWoodpostgresql+psycopg as allowed scheme for PostgreDsn to make it usable with SQLAlchemy 2, #4689 by @morianpatternProperties and additionalProperties, #4641 by @jpariseunique_items, #4568 by @mfulgoGenericModel with Callable param raising a TypeError, #4551 by @mfulgoStrictStr type annotation, #4538 by @sispdataclass_transform keyword argument name from field_descriptors to field_specifiers, #4500 by @samuelcolvin__post_init__ when dataclasses are inherited, #4487 by @PrettyWood4_300) strings/bytes as input to int fields, see
python/cpython#95778 and
CVE-2020-10735, #1477 by @samuelcolvintomllib on Python 3.11 when parsing mypy configuration, #4476 by @hauntsaninjaGenericModel cache to detect order of arguments in Union models, #4474 by @sveinugulist and dict as default_factory, #4457 by @samuelcolvin__hash__ method to pydantic.color.Color class, #4454 by @czakiRefactor the whole pydantic dataclass decorator to really act like its standard lib equivalent.
It hence keeps __eq__, __hash__, ... and makes comparison with its non-validated version possible.
It also fixes usage of frozen dataclasses in fields and usage of default_factory in nested dataclasses.
The support of Config.extra has been added.
Finally, config customization directly via a dict is now possible, #2557 by @PrettyWood
BREAKING CHANGES:
compiled boolean (whether pydantic is compiled with cython) has been moved from main.py to version.pyConfig.extra is supported, dataclass ignores by default extra arguments (like BaseModel)Fix PEP487 __set_name__ protocol in BaseModel for PrivateAttrs, #4407 by @tlambert03
Allow for custom parsing of environment variables via parse_env_var in Config, #4406 by @acmiyaguchi
Rename master to main, #4405 by @hramezani
Fix StrictStr does not raise ValidationError when max_length is present in Field, #4388 by @hramezani
Make SecretStr and SecretBytes hashable, #4387 by @chbndrhnns
Fix StrictBytes does not raise ValidationError when max_length is present in Field, #4380 by @JeanArhancet
Add support for bare type, #4375 by @hramezani
Support Python 3.11, including binaries for 3.11 in PyPI, #4374 by @samuelcolvin
Add support for re.Pattern, #4366 by @hramezani
Fix __post_init_post_parse__ is incorrectly passed keyword arguments when no __post_init__ is defined, #4361 by @hramezani
Fix implicitly importing ForwardRef and Callable from pydantic.typing instead of typing and also expose MappingIntStrAny, #4358 by @aminalaee
remove Any types from the dataclass decorator so it can be used with the disallow_any_expr mypy option, #4356 by @DetachHead
moved repo to pydantic/pydantic, #4348 by @yezz123
fix "extra fields not permitted" error when dataclass with Extra.forbid is validated multiple times, #4343 by @detachhead
Add Python 3.9 and 3.10 examples to docs, #4339 by @Bobronium
Discriminated union models now use oneOf instead of anyOf when generating OpenAPI schema definitions, #4335 by @MaxwellPayne
Allow type checkers to infer inner type of Json type. Json[list[str]] will be now inferred as list[str],
Json[Any] should be used instead of plain Json.
Runtime behaviour is not changed, #4332 by @Bobronium
Allow empty string aliases by using a alias is not None check, rather than bool(alias), #4253 by @sergeytsaplin
Update ForwardRefs in Field.outer_type_, #4249 by @JacobHayes
The use of __dataclass_transform__ has been replaced by typing_extensions.dataclass_transform, which is the preferred way to mark pydantic models as a dataclass under PEP 681, #4241 by @multimeric
Use parent model's Config when validating nested NamedTuple fields, #4219 by @synek
Update BaseModel.construct to work with aliased Fields, #4192 by @kylebamos
Catch certain raised errors in smart_deepcopy and revert to deepcopy if so, #4184 by @coneybeare
Add Config.anystr_upper and to_upper kwarg to constr and conbytes, #4165 by @satheler
Fix JSON schema for set and frozenset when they include default values, #4155 by @aminalaee
Teach the mypy plugin that methods decorated by @validator are classmethods, #4102 by @DMRobertson
Improve mypy plugin's ability to detect required fields, #4086 by @richardxia
Support fields of type Type[] in schema, #4051 by @aminalaee
Add default value in JSON Schema when const=True, #4031 by @aminalaee
Adds reserved word check to signature generation logic, #4011 by @strue36
Fix Json strategy failure for the complex nested field, #4005 by @sergiosim
Add JSON-compatible float constraint allow_inf_nan, #3994 by @tiangolo
Remove undefined behaviour when env_prefix had characters in common with env_nested_delimiter, #3975 by @arsenron
Support generics model with create_model, #3945 by @hot123s
allow submodels to overwrite extra field info, #3934 by @PrettyWood
Document and test structural pattern matching (PEP 636) on BaseModel, #3920 by @irgolic
Fix incorrect deserialization of python timedelta object to ISO 8601 for negative time deltas. Minus was serialized in incorrect place ("P-1DT23H59M59.888735S" instead of correct "-P1DT23H59M59.888735S"), #3899 by @07pepa
Fix validation of discriminated union fields with an alias when passing a model instance, #3846 by @chornsby
Add a CockroachDsn type to validate CockroachDB connection strings. The type
supports the following schemes: cockroachdb, cockroachdb+psycopg2 and cockroachdb+asyncpg, #3839 by @blubber
Fix MyPy plugin to not override pre-existing __init__ method in models, #3824 by @patrick91
Fix mypy version checking, #3783 by @KotlinIsland
support overwriting dunder attributes of BaseModel instances, #3777 by @PrettyWood
Added ConstrainedDate and condate, #3740 by @hottwaj
Support kw_only in dataclasses, #3670 by @detachhead
Add comparison method for Color class, #3646 by @aminalaee
Drop support for python3.6, associated cleanup, #3605 by @samuelcolvin
created new function to_lower_camel() for "non pascal case" camel case, #3463 by @schlerp
Add checks to default and default_factory arguments in Mypy plugin, #3430 by @klaa97
fix mangling of inspect.signature for BaseModel, #3413 by @fix-inspect-signature
Adds the SecretField abstract class so that all the current and future secret fields like SecretStr and SecretBytes will derive from it, #3409 by @expobrain
Support multi hosts validation in PostgresDsn, #3337 by @rglsk
Fix parsing of very small numeric timedelta values, #3315 by @samuelcolvin
Update SecretsSettingsSource to respect config.case_sensitive, #3273 by @JeanArhancet
Add MongoDB network data source name (DSN) schema, #3229 by @snosratiershad
Add support for multiple dotenv files, #3222 by @rekyungmin
Raise an explicit ConfigError when multiple fields are incorrectly set for a single validator, #3215 by @SunsetOrange
Allow ellipsis on Fields inside Annotated for TypedDicts required, #3133 by @ezegomez
Catch overflow errors in int_validator, #3112 by @ojii
Adds a __rich_repr__ method to Representation class which enables pretty printing with Rich, #3099 by @willmcgugan
Add percent encoding in AnyUrl and descendent types, #3061 by @FaresAhmedb
validate_arguments decorator now supports alias, #3019 by @MAD-py
Avoid __dict__ and __weakref__ attributes in AnyUrl and IP address fields, #2890 by @nuno-andre
Add ability to use Final in a field type annotation, #2766 by @uriyyo
Update requirement to typing_extensions>=4.1.0 to guarantee dataclass_transform is available, #4424 by @commonism
Add Explosion and AWS to main sponsors, #4413 by @samuelcolvin
Update documentation for copy_on_model_validation to reflect recent changes, #4369 by @samuelcolvin
Runtime warning if __slots__ is passed to create_model, __slots__ is then ignored, #4432 by @samuelcolvin
Add type hints to BaseSettings.Config to avoid mypy errors, also correct mypy version compatibility notice in docs, #4450 by @samuelcolvin
Pre-release, see the GitHub release for details.
Pre-release, see the GitHub release for details.
Pre-release, see the GitHub release for details.
Revert Breaking Change: v1.9.1 introduced a breaking change where model fields were
deep copied by default, this release reverts the default behaviour to match v1.9.0 and before,
while also allow deep-copy behaviour via copy_on_model_validation = 'deep'. See #4092 for more information.
Config.copy_on_model_validation is now a str which must be
'none', 'deep', or 'shallow' corresponding to not copying, deep copy & shallow copy; default 'shallow',
#4093 by @timkpaineThank you to pydantic's sponsors: @tiangolo, @stellargraph, @JonasKs, @grillazz, @Mazyod, @kevinalh, @chdsbd, @povilasb, @povilasb, @jina-ai, @mainframeindustries, @robusta-dev, @SendCloud, @rszamszur, @jodal, @hardbyte, @corleyma, @daddycocoaman, @Rehket, @jokull, @reillysiemens, @westonsteimel, @primer-io, @koxudaxi, @browniebroke, @stradivari96, @adriangb, @kamalgill, @jqueguiner, @dev-zero, @datarootsio, @RedCarpetUp for their kind support.
generics._generic_types_cache and generics._assigned_parameters
to avoid unlimited increase in memory usage, #4083 by @samuelcolvin__isinstancecheck__ on pydantic models when the type is not a model, may also avoid memory "leaks", #4081 by @samuelcolvinFieldInfo that caused problems with PEP 593 type aliases, #4067 by @adriangb__dataclass_transform__ when using pydantic.dataclasses.dataclass, #4006 by @giuliano-oliveiraClassVars in models, #3679 by @samuelcolvinConfig.copy_on_model_validation does a deep copy and not a shallow one, #3641 by @PrettyWoodread_text(encoding='utf-8') for setup.py, #3625 by @hswong3iThank you to pydantic's sponsors: @sthagen, @timdrijvers, @toinbis, @koxudaxi, @ginomempin, @primer-io, @and-semakin, @westonsteimel, @reillysiemens, @es3n1n, @jokull, @JonasKs, @Rehket, @corleyma, @daddycocoaman, @hardbyte, @datarootsio, @jodal, @aminalaee, @rafsaf, @jqueguiner, @chdsbd, @kevinalh, @Mazyod, @grillazz, @JonasKs, @simw, @leynier, @xfenix for their kind support.
Config.smart_union for better union logic, #2092 by @PrettyWoodfoo___bar, #3159 by @Air-Mark__dataclass_transform__, #2721 by @tiangoloupdate_forward_refs to Config.json_encodes prevent name clashes in types defined via strings, #3583 by @samuelcolvin0.910, 0.920, 0.921 & 0.930, #3573 & #3594 by @PrettyWood, @christianbundy, @samuelcolvinjson() by default, #3542 by @PrettyWood__root__ attribute from BaseModel, #3540 by @laydayextra fields with model __repr__, #3234 by @cocolmanConfig.copy_on_model_validation always have all fields, #3201 by @PrettyWoodDecimal-specific validation configurations in Field(), additionally to using condecimal(),
to allow better support from editors and tooling, #3507 by @tiangoloarm64 binaries suitable for MacOS with an M1 CPU to PyPI, #3498 by @samuelcolvinNone was considered invalid when using a Union type containing Any or object, #3444 by @tharradinefield argument (of type
pydantic.fields.ModelField) to __modify_schema__() if present, #3434 by @jasujmtyping.ClassVar string type annotation, #3401 by @uriyyotyping_extensions.TypedDict, #3374 by @BvB93name_must_contain_space to value_must_equal_bar, #3327 by @michaelrios28AmqpDsn class, #3254 by @kludexEnum value as default in generated JSON schema, #3190 by @joaommartinsvalidate_arguments now supports extra customization (used to always be Extra.forbid), #3161 by @PrettyWoodpydantic.utils.is_valid_field so that it ignores untyped private variables, #3146 by @hi-ogawavalidate_arguments issue with Config.validate_all, #3135 by @PrettyWoodobject type, #3062 by @PrettyWood_special properties on parent classes, #3043 by @zulrangTypedDict class for error objects, #3038 by @matthewhughes934create_model_from_typeddict mypy compliant, #3008 by @PrettyWoodPrivateAttr, #2989 by @hmvpUnion type with a complex subfield, #2936 by @cbartzStrictStr permitting Enum values where the enum inherits from str, #2929 by @samuelcolvinSecretsSettingsSource parse values being assigned to fields of complex types when sourced from a secrets file,
just as when sourced from environment variables, #2917 by @davidmreedpydantic-mypy plugin compatible with pyproject.toml configuration, consistent with mypy changes.
See the doc for more information, #2908 by @jrwalkJson[T], #2860 by @geekingfrogDeque fields, #2810 by @sergejkozinLiteral, #2794 by @PrettyWoodNamedTuple and TypedDict when they're used directly as the type of fields
within Pydantic models, #2760 by @jameysharpmypy plugin fails on construct method call for BaseSettings derived classes, #2753 by @uriyyopydantic.create_model function, #2748 by @uriyyoschema to schema_ to avoid shadowing of global variable name, #2724 by @shahriyarr__dataclass_transform__, #2721 by @tiangoloBaseConfig and handle max_length = 0, #2719 by @PrettyWoodorm_mode checking to allow recursive ORM mode parsing with dicts, #2718 by @nuno-andreNamedTuple and has a default value, #2707 by @PrettyWoodEnum fields now properly support extra kwargs in schema generation, #2697 by @sammchardyuniqueItems option to ConstrainedList, #2618 by @nuno-andre__version__ attribute to pydantic module, #2572 by @paxcodespostgresql+asyncpg, postgresql+pg8000, postgresql+psycopg2, postgresql+psycopg2cffi, postgresql+py-postgresql
and postgresql+pygresql schemes for PostgresDsn, #2567 by @postgres-asyncpgdecimal_places argument is specified, #2524 by @cwe5590collections.abc.Callable to be used as type in Python 3.9, #2519 by @daviskirksetup.py
to allow for custom CFLAGS when compiling, #2517 by @peterroelantsdefault_factory to run it only once even if Config.validate_all is set, #2515 by @PrettyWoodAnyUrl hosts. This allows urls with DNS labels
looking like IPs to validate as they are perfectly valid host names, #2512 by @sbv-csisminItems and maxItems in generated JSON schema for fixed-length tuples, #2497 by @PrettyWoodstrict argument to conbytes, #2489 by @koxudaxiGetterDict to docs, #2463 by @nuno-andreKafkaDsn type, HttpUrl now has default port 80 for http and 443 for https, #2447 by @MihanixAPastDate and FutureDate types, #2425 by @KludexGeneric fields with subtypes, #2375 by @maximbergNameEmail to str, #2341 by @alecgeronaConfig.smart_union to prevent coercion in Union if possible, see
the doc for more information, #2092 by @PrettyWoodtyping.Counter as a model field type, #2060 by @uriyyo__bases__ when constructing new parameterised classes, so that A <: B => A[int] <: B[int], #2007 by @diabolo-danFileUrl type that allows URLs that conform to RFC 8089.
Add host_required parameter, which is True by default (AnyUrl and subclasses), False in RedisDsn, FileUrl, #1983 by @vgerakconfrozenset(), analogous to conset() and conlist(), #1897 by @PrettyWoodroot_validator if overridden, #1895 by @PrettyWoodrepr (defaults to True) parameter to Field, to hide it from the default representation of the BaseModel, #1831 by @fnep!!! warning A security vulnerability, level "moderate" is fixed in v1.8.2. Please upgrade ASAP. See security advisory CVE-2021-29510
date and datetime parsing so passing either 'infinity' or float('inf')
(or their negative values) does not cause an infinite loop,
see security advisory CVE-2021-29510Literal of an enum member, #2536 by @PrettyWoodjson_encoders in class kwargs, #2521 by @layday__eq__, #2483 by @PrettyWoodAnnotated in validate_arguments and in generic models with Python 3.9, #2483 by @PrettyWoodBug fixes for regressions and new features from v1.8
Config.field to update elements of a Field, #2461 by @samuelcolvinBaseModel field and a custom root type, #2449 by @PrettyWoodPattern encoder to fastapi, #2444 by @PrettyWoodmultiple_of argument is specified, #2442 by @tobi-lipede-oodleRecursionError when using some types like Enum or Literal with generic models, #2436 by @PrettyWood__hash__ in subclasses of a model, #2422 by @PrettyWoodmypy complaints on Path and UUID related custom types, #2418 by @PrettyWoodThank you to pydantic's sponsors: @jorgecarleitao, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @koxudaxi, @timdrijvers, @mkeen, @meadsteve, @ginomempin, @primer-io, @and-semakin, @tomthorogood, @AjitZK, @westonsteimel, @Mazyod, @christippett, @CarlosDomingues, @Kludex, @r-m-n for their kind support.
NamedTuple and TypedDict, #2216 by @PrettyWoodAnnotated hints on model fields, #2147 by @JacobHayesfrozen parameter on Config to allow models to be hashed, #1880 by @rhuilleSchema which was replaced by FieldConfig.case_insensitive which was replaced by Config.case_sensitive (default False)Config.allow_population_by_alias which was replaced by Config.allow_population_by_field_namemodel.fields which was replaced by model.__fields__model.to_string() which was replaced by str(model)model.__values__ which was replaced by model.__dict__each_item.
There were indeed some edge cases with some compound types where the validated items were the last sublevel ones, #1933 by @PrettyWoodutils.lenient_issubclass to handle typing.GenericAlias objects like list[str] in Python >= 3.9, #2399 by @daviskirkdataclass by allowing the usage of pydantic Field or 'metadata' kwarg of dataclasses.field, #2384 by @PrettyWoodtyping-extensions a required dependency, #2368 by @samuelcolvinresolve_annotations more lenient, allowing for missing modules, #2363 by @samuelcolvinMapping subclasses from always being coerced to dict, #2325 by @ofekNone for type Optional[conset / conlist], #2320 by @PrettyWoodpython_requires metadata to require >=3.6.1, #2306 by @hukkinj1Decimal with, or without any decimal places, #2293 by @hultner__fields_set__ in BaseModel.copy(update=…), #2290 by @PrettyWoodBaseModel.construct(), #2281 by @PrettyWoodvalidate_decorator so **kwargs doesn't exclude values when the keyword
has the same name as the *args or **kwargs names, #2251 by @cybojenixvalidate_arguments, as per behaviour with native functions, #2249 by @cybojenixcon* type functions, #2242 by @tayoogunbiyi__root__) when using parse_obj() with nested models, #2238 by @PrettyWood__root__) with from_orm(), #2237 by @PrettyWoodNamedTuple and TypedDict types.
Those two types are now handled and validated when used inside BaseModel or pydantic dataclass.
Two utils are also added create_model_from_namedtuple and create_model_from_typeddict, #2216 by @PrettyWoodUnion[Type[...], ...], #2213 by @PrettyWoodTypeError when a root_validator does not return a dict (e.g. None), #2209 by @masalim2FrozenSet[str] type annotation to the allowed_schemes argument on the strict_url field type, #2198 by @Midnighterallow_mutation constraint to Field, #2195 by @sblack-usuField with a default_factory to be used as an argument to a function
decorated with validate_arguments, #2176 by @thomascobbLiteral field type, #2166 by @PrettyWoodtyping.Annotated hints on model fields. A Field may now be set in the type hint with Annotated[..., Field(...); all other annotations are ignored but still visible with get_type_hints(..., include_extras=True), #2147 by @JacobHayesStrictBytes type as well as strict=False option to ConstrainedBytes, #2136 by @rlizzoConfig.anystr_lower and to_lower kwarg to constr and conbytes, #2134 by @tayoogunbiyityping.Tuple type, #2132 by @PrettyWoodvalidate to functions decorated with validate_arguments
to validate parameters without actually calling the function, #2127 by @PrettyWoodNone, NoneType or Literal[None], #2095 by @PrettyWoodCallable with a default value, #2094 by @PrettyWoodcreate_model return type annotation to return type which inherits from __base__ argument, #2071 by @uriyyojson_encoders inheritance, #2064 by @art049ClassVars in sub-models without having to re-annotate them, #2061 by @laydayPattern type, #2045 by @PrettyWoodNonNegativeInt, NonPositiveInt, NonNegativeFloat, NonPositiveFloat, #1975 by @mdavis-xyzKeyError to be raised when building schema from multiple BaseModel with the same names declared in separate classes, #1912 by @JSextonnrediss (Redis over SSL) protocol to RedisDsn
Allow URLs without user part (e.g., rediss://:pass@localhost), #1911 by @TrDexfrozen boolean parameter to Config (default: False).
Setting frozen=True does everything that allow_mutation=False does, and also generates a __hash__() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable, #1880 by @rhuillePaymentCardNumber type, #1416 by @AlexanderSovRecursionError while using recursive GenericModels, #1370 by @xpptenum for typing.Literal in JSON schema, #1350 by @PrettyWoodupdate_forward_refs and silently behaved incorrectly, #1201 by @PrettyWooda: List[T] are considered to be concrete. This allows these models to be subclassed and composed as expected, #947 by @daviskirkConfig.copy_on_model_validation flag. When set to False, pydantic will keep models used as fields
untouched on validation instead of reconstructing (copying) them, #265 by @PrettyWooddate and datetime parsing so passing either 'infinity' or float('inf')
(or their negative values) does not cause an infinite loop,
See security advisory CVE-2021-29510Thank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api, @mkeen, @meadsteve for their kind support.
underscore_attrs_are_private with generic models, #2138 by @PrettyWoodroot_validator when validate_assignment is on, #2116 by @PrettyWoodpydantic.dataclasses.dataclass dynamically created from a built-in dataclasses.dataclass, #2111 by @aimestereo__doc__ as private attribute when Config.underscore_attrs_are_private is set, #2090 by @PrettyWoodGenericModel concrete model creation, allow GenericModel concrete name reusing in module, #2078 by @Bobroniumvalidate_assignment is set, #2073 by @PrettyWooddataclass when converted into pydantic dataclass, #2065 by @PrettyWoodThank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api, @mkeen for their kind support.
validate_arguments when passing configuration as argument, #2055 by @laydayPrivateAttr, #2048 by @aphedgesunderscore_attrs_are_private causing TypeError when overriding __init__, #2047 by @samuelcolvinvalidate_assignment=True, #2044 by @johnsabathdataclass can inherit from stdlib dataclass
and Config.arbitrary_types_allowed is supported, #2042 by @PrettyWoodThank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api for their kind support.
BaseSettings, thanks @mdgilene__field_defaults__, add default_factory support with BaseModel.construct.
Use .get_default() method on fields in __fields__ attribute instead, #1732 by @PrettyWoodvalues parameter type in BaseModel.__setattr__,
when validate_assignment = True in model config, #1999 by @me-ranshfields.Undefined to be a singleton object, fixing inherited generic model schemas, #1981 by @daviskirkmin_length/max_length constraints with secret types, #1974 by @uriyyoroot_validators when validate_assignment is on, #1971 by @PrettyWooddeque to field types, #1935 by @wozniaktyBaseSettings to read "secret files", #1820 by @mdgileneparse_raw_as utility function, #1812 by @PrettyWooddotenv files (e.g. ~/.env), #1803 by @PrettyWoodparse_file to show that the argument
should be a file path not a file-like object, #1794 by @mdavis-xyzBaseModel is named Model, #1770 by @selimbLiteral Enums when use_enum_values is True, #1747 by @noelevansZ for UTC
or an offset for absolute positive or negative time shifts. Or the timezone data can be omitted, #1744 by @noelevans__init__ with Python 3.6 signature for ForwardRef, #1738 by @sirtelemakEnum and IntEnum as valid types for fields, #1735 by @PrettyWood__module__ argument of create_model from None to 'pydantic.main'.
Set reference of created concrete model to it's module to allow pickling (not applied to models created in
functions), #1686 by @Bobroniumconfig to @validate_arguments, #1663 by @samuelcolvinenv in their Config. Previously only env_prefix configuration option was applicable, #1561 by @ojomioref_template when creating schema $refs, #1479 by @kilo59__call__ stub to PyObject so that mypy will know that it is callable, #1352 by @brianmaissypydantic.dataclasses.dataclass decorator now supports built-in dataclasses.dataclass.
It is hence possible to convert an existing dataclass easily to add Pydantic validation.
Moreover nested dataclasses are also supported, #744 by @PrettyWooddate and datetime parsing so passing either 'infinity' or float('inf')
(or their negative values) does not cause an infinite loop,
See security advisory CVE-2021-29510default_factory, #1710 by @PrettyWoodThank you to pydantic's sponsors: @matin, @tiangolo, @chdsbd, @jorgecarleitao, and 1 anonymous sponsor for their kind support.
conlist and conset to not have always=True, #1682 by @samuelcolvinAnyUrl (can't exceed 65536) ports are 16 unsigned bits: 0 <= port <= 2**16-1 src: rfc793 header format, #1654 by @flapiliregex anchoring semantics, #1648 by @yurikhanchain.from_iterable in class_validators.py. This is a faster and more idiomatic way of using itertools.chain.
Instead of computing all the items in the iterable and storing them in memory, they are computed one-by-one and never
stored as a huge list. This can save on both runtime and memory space, #1642 by @cool-RRconset(), analogous to conlist(), #1623 by @patrickkwangdotenv files, #1615 by @PrettyWoodSchemaExtraCallable is always defined to get type hints on BaseConfig, #1614 by @PrettyWoodAnyType alias for Type[Any], #1598 by @samuelcolvin__modify_schema__ on Enums apply to the enum schema rather than fields that use the enum, #1581 by @therefromhere__all__ key when used in conjunction with index keys in advanced include/exclude of fields that are sequences, #1579 by @xspirusList field defined in a parent class when each_item=True. Added an example to the docs illustrating this, #1566 by @samueldeklundschema.field_class_to_schema to support frozenset in schema, #1557 by @wangpeibao__modify_schema__ only for the field schema, #1552 by @PrettyWoodfield.validate_always in fields.py so the always parameter of validators work on inheritance, #1545 by @dcHHHb'\x12\x34\x56\x78' * 4. This was done to support BINARY(16) columns in sqlalchemy, #1541 by @shawnwalldefault_factory can return a singleton, #1523 by @therefromhereNameEmail.__eq__ so duplicate NameEmail instances are evaluated as equal, #1514 by @stephen-bunndefault_factory by calling it only once
if possible and by not setting a default value in the schema, #1491 by @PrettyWoodBaseModel.__signature__ class-only, so getting __signature__ from model instance will raise AttributeError, #1466 by @Bobronium'format': 'password' in the schema for secret types, #1424 by @atheuzConstrainedFloat so that exclusiveMinimum and
minimum are not included in the schema if they are equal to -math.inf and
exclusiveMaximum and maximum are not included if they are equal to math.inf, #1417 by @vdwees__root__ dicts in .dict() (and, by extension, in .json()), #1414 by @patrickkwangconst validator to post-validators so it validates the parsed value, #1410 by @selimbLiteral['foo', Literal['bar']], #1364 by @DBCerigouser_required = True from RedisDsn, neither user nor password are required, #1275 by @samuelcolvinallOf from schema for fields with Union and custom Field, #1209 by @mostaphaRoudsari$ref
property to point to the enum definition, #1173 by @calvinwyoungextra: allow never uses a field name, #1418 by @prettywoodField default value, #1412 by @prettywood.dict(), ._iter(), ..., immutable, #1404 by @AlexECXmodel._iter(), regardless of by_alias, #1397 by @AlexECXmodel.copy() does make a shallow copy of attributes, #1383 by @samuelcolvinmodel_name argument of main.create_model() to __model_name to allow using model_name as a field name, #1367 by @kittipatvtyping_extensions dependency for Python 3.8, #1342 by @prettywoodSecretStr and SecretBytes initialization idempotent, #1330 by @atheuzPaymentCardNumber, PaymentCardBrand now inherits from str, #1317 by @samuelcolvinBaseModel inherit from Representation to make mypy happy when overriding __str__, #1310 by @FuegoFroNone as input to all optional list fields, #1307 by @prettywooddatetime field to default_factory example, #1301 by @StephenBrown2'__all__', #1286 by @masalim2Optional, so that these are valid mypy annotations, #1248 by @kokespattern_validator() accept pre-compiled Pattern objects. Fix str_validator() return type to str, #1237 by @adamgregupdate_forward_refs() method of BaseModel now copies __dict__ of class module instead of modifying it, #1228 by @paul-ilyin@validate_arguments, #1222 by @samuelcolvindefault_factory argument to Field to create a dynamic default value by passing a zero-argument callable, #1210 by @prettywoodNewType of List, Optional, etc, #1207 by @Kazyroot_validator, #1192 by @samuelcolvinvalidate_arguments function decorator which checks the arguments to a function matches type annotations, #1179 by @samuelcolvin__signature__ to models, #1034 by @Bobronium._iter() method, 10x speed boost for dict(model), #1017 by @Bobroniumalias_generator to avoid buggy/unexpected behaviour,
see here for details, #1178 by @samuelcolvincls argument in validators during assignment, #1172 by @samuelcolvinPaymentCardNumber, #1166 by @cuencandres__get_validators__ like a custom data type, #1159 by @tiangoloIterable, #1152 by @tiangolourl_regex to accept schemas with +, - and . after the first character, #1142 by @samuelcolvinversion_info() to version.py, suggest its use in issues, #1138 by @samuelcolvinEmailStr and NameEmail to accept instances of themselves in cython, #1126 by @koxudaxiConfig.schema_extra callable, #1125 by @therefromhere__all__ to __init__.py to prevent "implicit reexport" errors from mypy, #1072 by @samuelcolvinBaseSettings, #1011 by @acnebsschema and schema_model to handle dataclasses by using their __pydantic_model__ feature, #792 by @aviramharoot_validator to be skipped if values validation fails using keyword skip_on_failure=True, #1049 by @aviramhaConfig.schema_extra to be a callable so that the generated schema can be post-processed, #1054 by @selimb__schema_attributes__ is True, #1064 by @samuelcolvinBaseModel.parse_file to use Config.json_loads, #1067 by @kierandarcyJson fields, #1073 by @volker48CYTHON_NTHREADS environment variable, #1074 by @samuelcolvin__eq__ to SecretStr and SecretBytes to allow "value equals", #1079 by @sbv-trueenergyConfig inheritance on BaseSettings when used with env_prefix, #1091 by @samuelcolvin__modify_schema__ when it conflicted with field_class_to_schema*, #1102 by @samuelcolvinBaseSettings subclass attributes, #1105 by @tribalsOptional with name: Optional[AnyType] = Field(...)
and refactor ModelField creation to preserve required parameter value, #1031 by @tiangolo;
see here for detailscattrs, #513 by @sebastianmikaexclude_none option to dict() and friends, #587 by @niknetnikovalideer, #670 by @gsakkisparse_obj_as and parse_file_as functions for ad-hoc parsing of data into arbitrary pydantic-compatible types, #934 by @dmontaguallow_reuse argument to validators, thus allowing validator reuse, #940 by @dmontaguByteSize type for converting byte string (1GB) to plain bytes, #977 by @dgasmith@root_validator(pre=True), #984 by @samuelcolvin__str__ and __repr__ inheritance for models, #1022 by @samuelcolvintyping.Literal for Python 3.8, #1026 by @dmontaguBaseModel.__init__ and more, #722 by @dmontaguGenericModel.__class_getitem__ to prevent PyCharm warnings, #936 by @dmontaguAny to allow None, also support TypeVar thus allowing use of un-parameterised collection types
e.g. Dict and List, #962 by @samuelcolvinFieldInfo on subfields to fix schema generation for complex nested types, #965 by @samuelcolvinModel.fields property, use Model.__fields__ instead, #883 by @samuelcolvinalias_generator, #904 by @samuelcolvinskip_defaults to exclude_unset, and add ability to exclude actual defaults, #915 by @dmontagu**kwargs to pydantic.main.ModelMetaclass.__new__ so __init_subclass__ can take custom parameters on extended
BaseModel classes, #867 by @retniktFutureWarning instead of DeprecationWarning when alias instead of env is used for settings models, #881 by @samuelcolvinBaseSettings inheritance and alias getting set to None, #882 by @samuelcolvin__repr__ and __str__ methods to be consistent across all public classes, add __pretty__ to support
python-devtools, #884 by @samuelcolvincase_insensitive on BaseSettings config, #885 by @samuelcolvinBaseSettings merge environment variables and in-code values recursively, as long as they create a valid object
when merged together, to allow splitting init arguments, #888 by @idmitrievskyModel.construct() to be more user-friendly, document construct() usage, #898 by @samuelcolvinconstruct() method, #907 by @ashearsField constraints on complex types, raise an error if constraints are not enforceable,
also support tuples with an ellipsis Tuple[X, ...], Sequence and FrozenSet in schema, #909 by @samuelcolvinstr/repr logic for ModelField, #912 by @samuelcolvinConstrainedList, update schema generation to reflect min_items and max_items Field() arguments, #917 by @samuelcolvininclude and exclude arguments of dict(), #921 by @samuelcolvinValidationError.json() by using pydantic_encoder, #922 by @samuelcolvinremove_untouched, improve error message for types with no validators, #926 by @retniktStrictBool typecheck as bool to allow for default values without mypy errors, #690 by @dmontaguGenericModel subclasses, #859 by @dmontaguif TYPE_CHECKING: to the excluded lines for test coverage, #874 by @dmontaguallow_population_by_alias to allow_population_by_field_name, remove unnecessary warning about it, #875 by @samuelcolvinSchema to Field, make it a function to placate mypy, #577 by @samuelcolvinbool, #617 by @dmontaguget_validators is no longer recognised, use __get_validators__.
Config.ignore_extra and Config.allow_extra are no longer recognised, use Config.extra, #720 by @samuelcolvinBaseSettings; case_insensitive renamed to case_sensitive,
default changed to case_sensitive = False, env_prefix default changed to '' - e.g. no prefix, #721 by @dmontaguroot_validator and rename root errors from __obj__ to __root__, #729 by @samuelcolvindict(model) so that sub-models are no longer
converted to dictionaries, #733 by @samuelcolvininitvars support to post_init_post_parse, #748 by @Raphael-C-AlmeidaBaseModel.json() only serialize the __root__ key for models with custom root, #752 by @dmontaguURL parsing logic, #755 by @samuelcolvinBaseSettings now uses the special env settings to define which environment variables to
read, not aliases, #847 by @samuelcolvinassert statements inside validators, #653 by @abduscopydantic.dataclasses.dataclass and subclassing pydantic.BaseModel, #710 by @maddosaurusjson_loads and json_dumps Config properties, #714 by @samuelcolvinmypy integration, #735 by @dmontagu__repr__ method to ErrorWrapper, #738 by @samuelcolvinFrozenSet members in dataclasses, and a better error when attempting to use types from the typing module that are not supported by Pydantic, #745 by @djpettipydantic.typing, #761 by @samuelcolvinErrorWrapper, ValidationError and datetime parsing, #763 by @samuelcolvindatetime/date/time/timedelta types: more descriptive errors,
change errors to value_error not type_error, support bytes, #766 by @samuelcolvinLiteral types with multiple allowed values, #770 by @dmontagutitle field in JSON schema by converting underscore to space, #772 by @skewtymypy --no-implicit-reexport for dataclasses, also respect --no-implicit-reexport in pydantic itself, #783 by @samuelcolvinPaymentCardNumber type, #790 by @matinadditionalProperties to false in schema for models with extra fields disallowed, #796 by @Code0x58EmailStr validation method now returns local part case-sensitive per RFC 5321, #798 by @henriklindgrenConstrainedFloat, ConstrainedInt and ConstrainedStr and added
StrictFloat and StrictInt classes, #799 by @DerRiddaNone and Optional, replace whole with each_item (inverse meaning, default False)
on validators, #803 by @samuelcolvinType[T] type hints, #807 by @timonbimonchange_exceptions, change how pydantic error are constructed, #819 by @samuelcolvinBaseModel-type model field causes a ValidationError during parsing, #820 by @dmontagugetter_dict on Config, modify GetterDict to be more like a Mapping object and thus easier to work with, #821 by @samuelcolvinTypeVar param on base GenericModel class, #842 by @zpencerqModel._schema_cache -> Model.__schema_cache__, Model._json_encoder -> Model.__json_encoder__,
Model._custom_root_type -> Model.__custom_root_type__, #851 by @samuelcolvin(Docs are available here)
__post_init__ usage with dataclass inheritance, fix #739 by @samuelcolvinSchema on GenericModel fields, #754 by @amitblvalidate_assignment is on, #724 by @YaraslauZhylkoValidationError error message, #676 by @dmontagu__getattr__ and rename __values__ to __dict__ on BaseModel,
deprecation warning on use __values__ attr, attributes access speed increased up to 14 times, #712 by @BobroniumForwardRef (without self-referencing annotations) in Python 3.6, #706 by @koxudaxischema_extra in Config sub-class, #663 by @tiangoloEnumError, #697 by @dmontagumultiple_of values, #652 by @justindujardinNewType and Literal, #649 by @dmontagualias_generator and field config conflict, #645 by @gmetzker and #658 by @BobroniumEnumError, #673 by @dmontagudict, json and copy, #648 by @BobroniumGenericModel for models with concrete parameterized fields, #672 by @dmontaguLiteral type, #651 by @dmontaguConfig.keep_untouched for custom descriptors support, #679 by @Bobroniuminspect.cleandoc internally to get model description, #657 by @tiangoloColor to schema generation, by @euri10__init__ are correctly processed while still allowing self as a
parameter, #644 by @lnaden and @dgasmith__post_init__, #606 by @HanaasagiGenericModel, #610 by @dmontagualias_generator support, #622 by @Bobroniumself as a field name in parse_obj, #632 by @samuelcolvinUnion when defining multiple types under an attribute's
annotation and showcase how the type-order can affect marshalling of provided values, #594 by @somada141conlist type, #583 by @hmvp__post_init_post_parse__ on dataclasses, #567 by @sevahopydantic.compiled on ipython, #573 by @dmontagu and @samuelcolvinStrictBool type, #579 by @cazgp_pydantic_post_init to execute dataclass' original __post_init__ before
validation, #560 by @HeavenVolkofflist, tuple, and set, #540 by @tiangolomanylinux binaries, some other performance improvements, #548 by @samuelcolvinIPvAnyAddress, IPvAnyInterface, IPvAnyNetwork #498 by @pilosuscreate_model, #526 by @dmontagu.dict(skip_keys=True) skipping values set via alias (this involves changing
validate_model() to always returns Tuple[Dict[str, Any], Set[str], Optional[ValidationError]]), #517 by @sommdIPv4Address, IPv6Address, IPv4Interface,
IPv6Interface, IPv4Network, IPv6Network #532 by @euri10Color type, #504 by @pilosus and @samuelcolvin.dict() with extra keys, #490 by @JaewonKimconst keyword in Schema, #434 by @Sean1708ForwardRef in sub-types, like Union, #464 by @tiangoloparse_obj to cope with dict-like objects, #472 by @samuelcolvinjson for Path, FilePath, and DirectoryPath objects, #473 by @mikegoodspeedIntEnum support, #444 by @potykionblack deprecation warnings after update, #451 by @pilosusForwardRef collection bug, #450 by @tigerwingsClassVars, #455 by @tyryluipaddress types, #333 by @pilosusSecretStr and SecretBytes types, #452 by @atheuzIPv{4,6,Any}Network and IPv{4,6,Any}Interface types from ipaddress stdlib, #333 by @pilosusdatetime types, #386 by @pilosusSequence support, #304 by @pilosusNoneIsNotAllowedError message, #414 by @YaraslauZhylkoIPvAnyAddress, IPv4Address and IPv6Address types, #333 by @pilosusparse_obj and similar methods, #405 by @erosenninValidationError.json, #406 by @laydaydir method for autocompletion in interactive sessions, #398 by @dgasmithForwardRef (and therefore from __future__ import annotations) with dataclasses, #397 by @samuelcolvinvalues, config and field is now permitted, eg. (cls, value, field),
however the variadic key word argument ("**kwargs") must be called kwargs, #388 by @samuelcolvinskip_defaults argument to BaseModel.dict() to allow skipping of fields that
were not explicitly set, signature of Model.construct() changed, #389 by @dgasmithpy.typed marker file for PEP-561 support, #391 by @je-lextra behaviour for multiple inheritance/mix-ins, #394 by @YaraslauZhylkoCallable type hint, fix #279 by @proofit404validator decorator, fix #375 by @tiangolomultiple_of constraint to ConstrainedDecimal, ConstrainedFloat, ConstrainedInt
and their related types condecimal, confloat, and conint #371, thanks @StephenBrown2ignore_extra and allow_extra Config fields in favor of extra, #352 by @liiightvalidate_all or validate_always, #381 by @samuelcolvin2e10, #385 by @samuelcolvinOptional fields, fix #361 by @samuelcolvinConstrainedBytes and conbytes types, #315 @Gr1NMANIFEST.in to include license in package .tar.gz, #358 by @samuelcolvinalways=True when the default is None or the type is optional, also prevent
whole validators being called for sub-fields, fix #132 by @samuelcolvinignore_extra=False and allow_population_by_alias=True, fix #257 by @samuelcolvinBaseConfig attributes min_anystr_length and max_anystr_length to
None by default, fix #349 in #350 by @tiangolotimedelta as number, #325 by @tiangolo: dict, : list,
: tuple and : set, #330 & #335 by @nkoninvalidate_assignment argument with config)ImportError with PyObject, #309 by @samuelcolvinget_validators to __get_validators__, deprecation warning on use of old name, #338 by @samuelcolvinClassVar by excluding such attributes from fields, #184 by @samuelcolvincreate_model to correctly use the passed __config__, #320 by @hugoduncanschema to schema module to generate top-level schemas from base models, #308 by @tiangoloSchema class to declare validation for str and numeric values, #311 by @tiangolo_schema to schema on fields, #318 by @samuelcolvincase_insensitive option to BaseSettings Config, #277 by @jasonkuhrtparse_date, #298 by @samuelcolvinPyObject = None, fix #305 by @samuelcolvinPattern type, fix #303 by @samuelcolvinbool to an int #264 by @nphyattBaseModel.copy() #249, @gangeforsBaseModel attribute #242UrlStr and urlstr types #236timedelta objects as values for properties of type timedelta (matches datetime etc. behavior) #247typing.Any #237by_alias argument in .dict() and .json() model methods #205NewType support #115list, set & tuple validation #225validate_model method, allow errors to be returned along with valid values #221list, tuple and set types stricter #86FilePath and DirectoryPath types #10Config.allow_population_by_alias #160, thanks @bendemareeConfig.min_number_size and Config.max_number_size #183, thanks @Gr1Nlt and gt arguments to conint etc. #188
for the old behaviour use le and ge #194, thanks @jahebaConfig.error_msg_templates #183,
thanks @Gr1Nget_field_config on config classes #159UUID1, UUID3, UUID4 and UUID5 types #167, thanks @Gr1NDecimal, ConstrainedDecimal and condecimal types #170, thanks @Gr1Nparse_date() and parse_datetime() when input is 0 #144, thanks @YannLuoConfig.anystr_strip_whitespace and strip_whitespace kwarg to constr,
by default values is False #163, thanks @Gr1NConstrainedFloat, confloat, PositiveFloat and NegativeFloat types #166, thanks @Gr1Ninherit_config #139create_model modifying the base classcreate_model method #113 #125.config to .__config__ on a model.values() on a model, use .dict() insteadOrderedDict and use simple dict #126Config.use_enum_values #127@validate('*') #128README.rst presentSettingsvalidator decorators for complex validation, #97values(...) and replace with .dict(...), #99UUID validation #89index and track from error object (json) if they're null #90truncateparse_obj, parse_raw and parse_file helper functions #58config.allow_mutation = False, associated cleanup and performance improvement #44construct() and copy() #53setattr is removed as __setattr__ is now intelligent #44raise_exception removed, Models now always raise exceptions #44StrictStr which only always strings as input #52v0.2 this should fix itvalues() on a model is now a method not a property,
takes include and exclude argumentsto_string(pretty=True) method for models