
Security News
PyPI Expands Trusted Publishing to GitLab Self-Managed as Adoption Passes 25 Percent
PyPI adds Trusted Publishing support for GitLab Self-Managed as adoption reaches 25% of uploads
csvcubed-pydantic
Advanced tools
Data validation and settings management using Python type hinting.
Fast and extensible, pydantic plays nicely with your linters/IDE/brain. Define how data should be in pure, canonical Python 3.6+; validate it with pydantic.
See documentation for more details.
Install using pip install -U pydantic or conda install pydantic -c conda-forge.
For more installation options to make pydantic even faster,
see the Install section in the documentation.
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
class User(BaseModel):
id: int
name = 'John Doe'
signup_ts: Optional[datetime] = None
friends: List[int] = []
external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']}
user = User(**external_data)
print(user)
#> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
print(user.id)
#> 123
For guidance on setting up a development environment and how to make a contribution to pydantic, see Contributing to Pydantic.
See our security policy.
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 @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 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 @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 modyfying 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 nolonger
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 @tiangolomultiple_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 modelsFAQs
Data validation and settings management using python 3.6 type hinting
We found that csvcubed-pydantic demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
PyPI adds Trusted Publishing support for GitLab Self-Managed as adoption reaches 25% of uploads

Research
/Security News
A malicious Chrome extension posing as an Ethereum wallet steals seed phrases by encoding them into Sui transactions, enabling full wallet takeover.

Security News
Socket is heading to London! Stop by our booth or schedule a meeting to see what we've been working on.