NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI · #18 most downloaded on PyPI
Data validation using Python type hints
Last release 20 days ago
09 Sep 2026
Ships fairly regularly
a new release about every 3 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
2 versions withdrawn
withdrawn after publishing
9 years old
206 releases · first in 2017
Thank you to pydantic's sponsors: @tiangolo, @stellargraph, @JonasKs, @grillazz, @Mazyod, @kevinalh, @chdsbd, @povilasb, @povilasb, @jina-ai, @mainfra
Thank 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 @hswong3iOne column per quarter.
Thank you to pydantic's sponsors: @sthagen, @timdrijvers, @toinbis, @koxudaxi, @ginomempin, @primer-io, @and-semakin, @westonsteimel, @reillysiemens,
Thank 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 @fnepsupport generic models with discriminated union, #3551 by @PrettyWood
json() 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 @PrettyWoodFull Changelog: https://github.com/samuelcolvin/pydantic/compare/v1.9.0a1...v1.9.0a2
Discussion and feedback: #3538
Thank you to pydantic's sponsors: @timdrijvers, @toinbis, @koxudaxi, @ginomempin, @primer-io, @and-semakin, @westonsteimel, @reillysiemens, @es3n1n, @
See Changelog.
Thank you to pydantic's sponsors: @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 for their kind support.
Config.smart_union for better union logic, #2092 by @PrettyWoodfoo___bar, #3159 by @Air-Mark__dataclass_transform__, #2721 by @tiangoloDecimal-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.dict / .json export time, #660 by @daviskirkFull List of changes: https://github.com/samuelcolvin/pydantic/compare/v1.8.2...v1.9.0a1
A security vulnerability, level "moderate" is fixed in v1.8.2. Please upgrade ASAP. See security advisory CVE-2021-29510.
See Changelog.
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 in v1.8
See Changelog.
Bug fixes for regressions and new features in 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 @PrettyWoodBreaking Change, remove old deprecation aliases from v1, #2415 by @samuelcolvin:
See Changelog.
Thank 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 @PrettyWood…cause an infinite loop, see security advisory CVE-2021-29510.
Security fix: Fix 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-29510.
Thank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api, @mk
See Changelog.
Thank 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 @PrettyWoodThank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api, @mk
See Changelog.
Thank you to pydantic's sponsors: @timdrijvers, @BCarley, @chdsbd, @tiangolo, @matin, @linusg, @kevinalh, @jorgecarleitao, @koxudaxi, @primer-api, @mkeen for their kind support.
GenericModel concrete model creation, allow GenericModel concrete name reusing in module, #2078 by @MrMrRobatvalidate_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, @mk
See Changelog.
Thank 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 @PrettyWoodBreaking Change: remove __field_defaults__, add default_factory support with BaseModel.construct. Use .get_default() method on fields in __fields__ at…
See Changelog.
Thank 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 @MrMrRobatconfig 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 @PrettyWood…cause an infinite loop, see security advisory CVE-2021-29510.
Security fix: Fix 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-29510.
Thank you to pydantic's sponsors: @matin, @tiangolo, @chdsbd, @jorgecarleitao, and 1 anonymous sponsor for their kind support.
See Changelog.
Thank you to pydantic's sponsors: @matin, @tiangolo, @chdsbd, @jorgecarleitao, and 1 anonymous sponsor for their kind support.
changes:
default_factory, #1710 by @PrettyWoodThank you to pydantic's sponsors: @matin, @tiangolo, @chdsbd, @jorgecarleitao, and 1 anonymous sponsor for their kind support.
See Changelog.
Thank you to pydantic's sponsors: @matin, @tiangolo, @chdsbd, @jorgecarleitao, and 1 anonymous sponsor for their kind support.
changes:
conlist and conset to not have always=True, #1682 by @samuelcolvinAnyUrl (can't exceed 65536) ports are 16 insigned 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 @MrMrRobat'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 @calvinwyoungSignature generation with extra: allow never uses a field name, #1418 by @prettywood
See Changelog.
extra: allow never uses a field name, #1418 by @prettywoodField default value, #1412 by @prettywoodMake includes/excludes arguments for .dict(), ._iter(), ..., immutable, #1404 by @AlexECX
See Changelog.
.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 @MrMrRobat._iter() method, 10x speed boost for dict(model), #1017 by @MrMrRobatBreaking Change: alias precedence logic changed so aliases on a field always take priority over an alias from alias_generator to avoid buggy/unexpecte…
See Changelog.
alias_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 @acnebsChange schema and schema_model to handle dataclasses by using their __pydantic_model__ feature, #792 by @aviramha
See Changelog.
schema 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 @tribalsAdd benchmarks for cattrs, #513 by @sebastianmika
See Changelog.
cattrs, #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 @dmontaguOptional with name: Optional[AnyType] = Field(...) and refactor ModelField creation to preserve required parameter value, #1031 by @tiangoloFix bug where use of complex fields on sub-models could cause fields to be incorrectly configured, #1015 by @samuelcolvin
See Changelog.
Add a mypy plugin for type checking BaseModel.__init__ and more, #722 by @dmontagu
See Changelog.
BaseModel.__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 @samuelcolvinBreaking Change: deprecate the Model.fields property, use Model.__fields__ instead, #883 by @samuelcolvin
See Changelog.
Model.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 @retniktMark StrictBool typecheck as bool to allow for default values without mypy errors, #690 by @dmontagu
StrictBool 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 @samuelcolvinsee HISTORY.md
see HISTORY.rst
see HISTORY.rst
Schema 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 @samuelcolvinfix __post_init__ usage with dataclass inheritance, fix #739 by @samuelcolvin
__post_init__ usage with dataclass inheritance, fix #739 by @samuelcolvinSchema on GenericModel fields, #754 by @amitbldo not validate extra fields when validate_assignment is on, #724 by @YaraslauZhylko
see HISTORY.rst:
validate_assignment is on, #724 by @YaraslauZhylkobreaking change: remove __getattr__ and rename __values__ to __dict__ on BaseModel, deprecation warning on use __values__ attr, attributes access spee…
ValidationError 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 @tiangolofix json generation for EnumError, #697 by @dmontagu
EnumError, #697 by @dmontagubetter support for floating point multiple_of values, #652 by @justindujardin
multiple_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 @euri10see HISTORY.rst and #664 for rationale behind patch release.
see HISTORY.rst and #664 for rationale behind patch release.
__init__ are correctly processed while still allowing self as a
parameter, #644 by @lnaden and @dgasmithenforce single quotes in code, #612 by @samuelcolvin
__post_init__, #606 by @HanaasagiGenericModel, #610 by @dmontagualias_generator support, #622 by @Bobroniumself as a field name in parse_obj, #632 by @samuelcolvinsupport dataclasses.InitVar, #592 by @pfrederiks
Union 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 @hmvpfix support for JSON Schema generation when using models with circular references in Python 3.7, #572 by @tiangolo
__post_init_post_parse__ on dataclasses, #567 by @sevahopydantic.compiled on ipython, #573 by @dmontagu and @samuelcolvinStrictBool type, #579 by @cazgpbreaking change _pydantic_post_init to execute dataclass' original __post_init__ before validation, #560 by @HeavenVolkoff
_pydantic_post_init to execute dataclass' original __post_init__ before
validation, #560 by @HeavenVolkoffThis is a pre-release to test manylinux binaries.
see HISTORY.rst.
This is a pre-release to test manylinux binaries.
Not for production use.
Breaking Change: fix .dict(skip_keys=True) skipping values set via alias (this involves changing validate_model() to always returns Tuple[Dict[str, An…
IPvAnyAddress, 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 @samuelcolvinImprove documentation on self-referencing models and annotations, #487 by @theenglishway
fix handling ForwardRef in sub-types, like Union, #464 by @tiangolo
ForwardRef 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 @mikegoodspeedfix black deprecation warnings after update, #451 by @pilosus
IntEnum 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 @atheuzadd IPv{4,6,Any}Network and IPv{4,6,Any}Interface types from ipaddress stdlib, #333 by @pilosus
Nothing published for this version
fix type hints of parse_obj and similar methods, #405 by @erosennin
Nothing published for this version
Nothing published for this version
Nothing published for this version
Fix to schema generation with Optional fields, fix #361 by @samuelcolvin
Optional fields, fix #361 by @samuelcolvinadd ConstrainedBytes and conbytes types, #315 @Gr1N
Nothing published for this version
Nothing published for this version
fix create_model to correctly use the passed __config__, #320 by @hugoduncan
create_model to correctly use the passed __config__, #320 by @hugoduncanNothing published for this version
Nothing published for this version
Nothing published for this version
fix issue where int_validator doesn't cast a bool to an int #264 by @nphyatt
Nothing published for this version
fix schema generation for fields defined using typing.Any #237
typing.Any #237Nothing published for this version
fix list, set & tuple validation #225
support Python 3.7 #216, thanks @layday
Your coding agent can read these notes before it upgrades. Set up the MCP server →