# Table of Contents - [Welcome to Pydantic - Pydantic](#welcome-to-pydantic-pydantic) - [Contributing - Pydantic](#contributing-pydantic) - [Installation - Pydantic](#installation-pydantic) - [Aliases - Pydantic](#aliases-pydantic) - [Pydantic People - Pydantic](#pydantic-people-pydantic) - [Annotated Handlers - Pydantic](#annotated-handlers-pydantic) - [Help with Pydantic - Pydantic](#help-with-pydantic-pydantic) - [Changelog - Pydantic](#changelog-pydantic) - [Migration Guide - Pydantic](#migration-guide-pydantic) - [Version Policy - Pydantic](#version-policy-pydantic) - [Why use Pydantic - Pydantic](#why-use-pydantic-pydantic) - [Configuration - Pydantic](#configuration-pydantic) - [Errors - Pydantic](#errors-pydantic) - [Pydantic Dataclasses - Pydantic](#pydantic-dataclasses-pydantic) - [Experimental - Pydantic](#experimental-pydantic) - [BaseModel - Pydantic](#basemodel-pydantic) - [Network Types - Pydantic](#network-types-pydantic) - [Fields - Pydantic](#fields-pydantic) - [Functional Serializers - Pydantic](#functional-serializers-pydantic) - [pydantic_core - Pydantic](#pydantic-core-pydantic) - [Functional Validators - Pydantic](#functional-validators-pydantic) - [ISBN - Pydantic](#isbn-pydantic) - [Currency - Pydantic](#currency-pydantic) - [Coordinate - Pydantic](#coordinate-pydantic) - [Country - Pydantic](#country-pydantic) - [Color - Pydantic](#color-pydantic) - [Mac Address - Pydantic](#mac-address-pydantic) - [Pendulum - Pydantic](#pendulum-pydantic) - [Script Code - Pydantic](#script-code-pydantic) - [Semantic Version - Pydantic](#semantic-version-pydantic) - [Timezone Name - Pydantic](#timezone-name-pydantic) - [ULID - Pydantic](#ulid-pydantic) - [RootModel - Pydantic](#rootmodel-pydantic) - [Language - Pydantic](#language-pydantic) --- # Welcome to Pydantic - Pydantic Pydantic[¶](#pydantic "Permanent link") ======================================== [![CI](https://img.shields.io/github/actions/workflow/status/pydantic/pydantic/ci.yml?branch=main&logo=github&label=CI)](https://github.com/pydantic/pydantic/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) [![Coverage](https://coverage-badge.samuelcolvin.workers.dev/pydantic/pydantic.svg)](https://github.com/pydantic/pydantic/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) [![pypi](https://img.shields.io/pypi/v/pydantic.svg)](https://pypi.python.org/pypi/pydantic) [![CondaForge](https://img.shields.io/conda/v/conda-forge/pydantic.svg)](https://anaconda.org/conda-forge/pydantic) [![downloads](https://static.pepy.tech/badge/pydantic/month)](https://pepy.tech/project/pydantic) [![license](https://img.shields.io/github/license/pydantic/pydantic.svg)](https://github.com/pydantic/pydantic/blob/main/LICENSE) [![llms.txt](https://img.shields.io/badge/llms.txt-green)](https://docs.pydantic.dev/latest/llms.txt) Documentation for version: [v2.11.3](https://github.com/pydantic/pydantic/releases/tag/v2.11.3) . Pydantic is the most widely used data validation library for Python. Fast and extensible, Pydantic plays nicely with your linters/IDE/brain. Define how data should be in pure, canonical Python 3.9+; validate it with Pydantic. Monitor Pydantic with Logfire ![🔥](https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/svg/1f525.svg ":fire:") Built by the same team as Pydantic, **[Logfire](https://pydantic.dev/logfire) ** is an application monitoring tool that is as simple to use and powerful as Pydantic itself. Logfire integrates with many popular Python libraries including FastAPI, OpenAI and Pydantic itself, so you can use Logfire to monitor Pydantic validations and understand why some inputs fail validation: Monitoring Pydantic with Logfire `from datetime import datetime import logfire from pydantic import BaseModel logfire.configure() logfire.instrument_pydantic() # (1)! class Delivery(BaseModel): timestamp: datetime dimensions: tuple[int, int] # this will record details of a successful validation to logfire m = Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10', '20']) print(repr(m.timestamp)) #> datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=TzInfo(UTC)) print(m.dimensions) #> (10, 20) Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10']) # (2)!` 1. Set logfire record all both successful and failed validations, use `record='failure'` to only record failed validations, [learn more](https://logfire.pydantic.dev/docs/integrations/pydantic/) . 2. This will raise a `ValidationError` since there are too few `dimensions`, details of the input data and validation errors will be recorded in Logfire. Would give you a view like this in the Logfire platform: [![Logfire Pydantic Integration](img/logfire-pydantic-integration.png)](https://logfire.pydantic.dev/docs/guides/web-ui/live/) This is just a toy example, but hopefully makes clear the potential value of instrumenting a more complex application. **[Learn more about Pydantic Logfire](https://logfire.pydantic.dev/docs/) ** Why use Pydantic?[¶](#why-use-pydantic "Permanent link") --------------------------------------------------------- * **Powered by type hints** — with Pydantic, schema validation and serialization are controlled by type annotations; less to learn, less code to write, and integration with your IDE and static analysis tools. [Learn more…](why/#type-hints) * **Speed** — Pydantic's core validation logic is written in Rust. As a result, Pydantic is among the fastest data validation libraries for Python. [Learn more…](why/#performance) * **JSON Schema** — Pydantic models can emit JSON Schema, allowing for easy integration with other tools. [Learn more…](why/#json-schema) * **Strict** and **Lax** mode — Pydantic can run in either strict mode (where data is not converted) or lax mode where Pydantic tries to coerce data to the correct type where appropriate. [Learn more…](why/#strict-lax) * **Dataclasses**, **TypedDicts** and more — Pydantic supports validation of many standard library types including `dataclass` and `TypedDict`. [Learn more…](why/#dataclasses-typeddict-more) * **Customisation** — Pydantic allows custom validators and serializers to alter how data is processed in many powerful ways. [Learn more…](why/#customisation) * **Ecosystem** — around 8,000 packages on PyPI use Pydantic, including massively popular libraries like _FastAPI_, _huggingface_, _Django Ninja_, _SQLModel_, & _LangChain_. [Learn more…](why/#ecosystem) * **Battle tested** — Pydantic is downloaded over 70M times/month and is used by all FAANG companies and 20 of the 25 largest companies on NASDAQ. If you're trying to do something with Pydantic, someone else has probably already done it. [Learn more…](why/#using-pydantic) [Installing Pydantic](install/) is as simple as: `pip install pydantic` Pydantic examples[¶](#pydantic-examples "Permanent link") ---------------------------------------------------------- To see Pydantic at work, let's start with a simple example, creating a custom class that inherits from `BaseModel`: Validation Successful `from datetime import datetime from pydantic import BaseModel, PositiveInt class User(BaseModel): id: int # (1)! name: str = 'John Doe' # (2)! signup_ts: datetime | None # (3)! tastes: dict[str, PositiveInt] # (4)! external_data = { 'id': 123, 'signup_ts': '2019-06-01 12:22', # (5)! 'tastes': { 'wine': 9, b'cheese': 7, # (6)! 'cabbage': '1', # (7)! }, } user = User(**external_data) # (8)! print(user.id) # (9)! #> 123 print(user.model_dump()) # (10)! """ { 'id': 123, 'name': 'John Doe', 'signup_ts': datetime.datetime(2019, 6, 1, 12, 22), 'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1}, } """` 1. `id` is of type `int`; the annotation-only declaration tells Pydantic that this field is required. Strings, bytes, or floats will be coerced to integers if possible; otherwise an exception will be raised. 2. `name` is a string; because it has a default, it is not required. 3. `signup_ts` is a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) field that is required, but the value `None` may be provided; Pydantic will process either a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time) integer (e.g. `1496498400`) or a string representing the date and time. 4. `tastes` is a dictionary with string keys and positive integer values. The `PositiveInt` type is shorthand for `Annotated[int, annotated_types.Gt(0)]`. 5. The input here is an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formatted datetime, but Pydantic will convert it to a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) object. 6. The key here is `bytes`, but Pydantic will take care of coercing it to a string. 7. Similarly, Pydantic will coerce the string `'1'` to the integer `1`. 8. We create instance of `User` by passing our external data to `User` as keyword arguments. 9. We can access fields as attributes of the model. 10. We can convert the model to a dictionary with [`model_dump()`](api/base_model/#pydantic.BaseModel.model_dump) . If validation fails, Pydantic will raise an error with a breakdown of what was wrong: Validation Error `# continuing the above example... from datetime import datetime from pydantic import BaseModel, PositiveInt, ValidationError class User(BaseModel): id: int name: str = 'John Doe' signup_ts: datetime | None tastes: dict[str, PositiveInt] external_data = {'id': 'not an int', 'tastes': {}} # (1)! try: User(**external_data) # (2)! except ValidationError as e: print(e.errors()) """ [ { 'type': 'int_parsing', 'loc': ('id',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'not an int', 'url': 'https://errors.pydantic.dev/2/v/int_parsing', }, { 'type': 'missing', 'loc': ('signup_ts',), 'msg': 'Field required', 'input': {'id': 'not an int', 'tastes': {}}, 'url': 'https://errors.pydantic.dev/2/v/missing', }, ] """` 1. The input data is wrong here — `id` is not a valid integer, and `signup_ts` is missing. 2. Trying to instantiate `User` will raise a [`ValidationError`](api/pydantic_core/#pydantic_core.ValidationError) with a list of errors. Who is using Pydantic?[¶](#who-is-using-pydantic "Permanent link") ------------------------------------------------------------------- Hundreds of organisations and packages are using Pydantic. Some of the prominent companies and organizations around the world who are using Pydantic include: [![Adobe](logos/adobe_logo.png)](why/#org-adobe "Adobe") [![Amazon and AWS](logos/amazon_logo.png)](why/#org-amazon "Amazon and AWS") [![Anthropic](logos/anthropic_logo.png)](why/#org-anthropic "Anthropic") [![Apple](logos/apple_logo.png)](why/#org-apple "Apple") [![ASML](logos/asml_logo.png)](why/#org-asml "ASML") [![AstraZeneca](logos/astrazeneca_logo.png)](why/#org-astrazeneca "AstraZeneca") [![Cisco Systems](logos/cisco_logo.png)](why/#org-cisco "Cisco Systems") [![Comcast](logos/comcast_logo.png)](why/#org-comcast "Comcast") [![Datadog](logos/datadog_logo.png)](why/#org-datadog "Datadog") [![Facebook](logos/facebook_logo.png)](why/#org-facebook "Facebook") [![GitHub](logos/github_logo.png)](why/#org-github "GitHub") [![Google](logos/google_logo.png)](why/#org-google "Google") [![HSBC](logos/hsbc_logo.png)](why/#org-hsbc "HSBC") [![IBM](logos/ibm_logo.png)](why/#org-ibm "IBM") [![Intel](logos/intel_logo.png)](why/#org-intel "Intel") [![Intuit](logos/intuit_logo.png)](why/#org-intuit "Intuit") [![Intergovernmental Panel on Climate Change](logos/ipcc_logo.png)](why/#org-ipcc "Intergovernmental Panel on Climate Change") [![JPMorgan](logos/jpmorgan_logo.png)](why/#org-jpmorgan "JPMorgan") [![Jupyter](logos/jupyter_logo.png)](why/#org-jupyter "Jupyter") [![Microsoft](logos/microsoft_logo.png)](why/#org-microsoft "Microsoft") [![Molecular Science Software Institute](logos/molssi_logo.png)](why/#org-molssi "Molecular Science Software Institute") [![NASA](logos/nasa_logo.png)](why/#org-nasa "NASA") [![Netflix](logos/netflix_logo.png)](why/#org-netflix "Netflix") [![NSA](logos/nsa_logo.png)](why/#org-nsa "NSA") [![NVIDIA](logos/nvidia_logo.png)](why/#org-nvidia "NVIDIA") [![OpenAI](logos/openai_logo.png)](why/#org-openai "OpenAI") [![Oracle](logos/oracle_logo.png)](why/#org-oracle "Oracle") [![Palantir](logos/palantir_logo.png)](why/#org-palantir "Palantir") [![Qualcomm](logos/qualcomm_logo.png)](why/#org-qualcomm "Qualcomm") [![Red Hat](logos/redhat_logo.png)](why/#org-redhat "Red Hat") [![Revolut](logos/revolut_logo.png)](why/#org-revolut "Revolut") [![Robusta](logos/robusta_logo.png)](why/#org-robusta "Robusta") [![Salesforce](logos/salesforce_logo.png)](why/#org-salesforce "Salesforce") [![Starbucks](logos/starbucks_logo.png)](why/#org-starbucks "Starbucks") [![Texas Instruments](logos/ti_logo.png)](why/#org-ti "Texas Instruments") [![Twilio](logos/twilio_logo.png)](why/#org-twilio "Twilio") [![Twitter](logos/twitter_logo.png)](why/#org-twitter "Twitter") [![UK Home Office](logos/ukhomeoffice_logo.png)](why/#org-ukhomeoffice "UK Home Office") For a more comprehensive list of open-source projects using Pydantic see the [list of dependents on github](https://github.com/pydantic/pydantic/network/dependents) , or you can find some awesome projects using Pydantic in [awesome-pydantic](https://github.com/Kludex/awesome-pydantic) . Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Contributing - Pydantic Contributing ============ We'd love you to contribute to Pydantic! Issues[¶](#issues "Permanent link") ------------------------------------ Questions, feature requests and bug reports are all welcome as [discussions or issues](https://github.com/pydantic/pydantic/issues/new/choose) . **However, to report a security vulnerability, please see our [security policy](https://github.com/pydantic/pydantic/security/policy) .** To make it as simple as possible for us to help you, please include the output of the following call in your issue: `python -c "import pydantic.version; print(pydantic.version.version_info())"` If you're using Pydantic prior to **v2.0** please use: `python -c "import pydantic.utils; print(pydantic.utils.version_info())"` Please try to always include the above unless you're unable to install Pydantic or **know** it's not relevant to your question or feature request. Pull Requests[¶](#pull-requests "Permanent link") -------------------------------------------------- It should be extremely simple to get started and create a Pull Request. Pydantic is released regularly so you should see your improvements release in a matter of days or weeks 🚀. Unless your change is trivial (typo, docs tweak etc.), please create an issue to discuss the change before creating a pull request. Pydantic V1 is in maintenance mode Pydantic v1 is in maintenance mode, meaning that only bug fixes and security fixes will be accepted. New features should be targeted at Pydantic v2. To submit a fix to Pydantic v1, use the `1.10.X-fixes` as a target branch. If you're looking for something to get your teeth into, check out the ["help wanted"](https://github.com/pydantic/pydantic/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) label on github. To make contributing as easy and fast as possible, you'll want to run tests and linting locally. Luckily, Pydantic has few dependencies, doesn't require compiling and tests don't need access to databases, etc. Because of this, setting up and running the tests should be very simple. Tip **tl;dr**: use `make format` to fix formatting, `make` to run tests and linting and `make docs` to build the docs. ### Prerequisites[¶](#prerequisites "Permanent link") You'll need the following prerequisites: * Any Python version between **Python 3.9 and 3.12** * [**uv**](https://docs.astral.sh/uv/getting-started/installation/) or other virtual environment tool * **git** * **make** ### Installation and setup[¶](#installation-and-setup "Permanent link") Fork the repository on GitHub and clone your fork locally. `# Clone your fork and cd into the repo directory git clone [[email protected]](/cdn-cgi/l/email-protection) :/pydantic.git cd pydantic # Install UV and pre-commit # We use pipx here, for other options see: # https://docs.astral.sh/uv/getting-started/installation/ # https://pre-commit.com/#install # To get pipx itself: # https://pypa.github.io/pipx/ pipx install uv pipx install pre-commit # Install pydantic, dependencies, test dependencies and doc dependencies make install` ### Check out a new branch and make your changes[¶](#check-out-a-new-branch-and-make-your-changes "Permanent link") Create a new branch for your changes. `# Checkout a new branch and make your changes git checkout -b my-new-feature-branch # Make your changes...` ### Run tests and linting[¶](#run-tests-and-linting "Permanent link") Run tests and linting locally to make sure everything is working as expected. ``# Run automated code formatting and linting make format # Pydantic uses ruff, an awesome Python linter written in rust # https://github.com/astral-sh/ruff # Run tests and linting make # There are a few sub-commands in Makefile like `test`, `testcov` and `lint` # which you might want to use, but generally just `make` should be all you need. # You can run `make help` to see more options.`` ### Build documentation[¶](#build-documentation "Permanent link") If you've made any changes to the documentation (including changes to function signatures, class definitions, or docstrings that will appear in the API documentation), make sure it builds successfully. We use `mkdocs-material[imaging]` to support social previews. You can find directions on how to install the required dependencies [here](https://squidfunk.github.io/mkdocs-material/plugins/requirements/image-processing/) . ``# Build documentation make docs # If you have changed the documentation, make sure it builds successfully. # You can also use `uv run mkdocs serve` to serve the documentation at localhost:8000`` If this isn't working due to issues with the imaging plugin, try commenting out the `social` plugin line in `mkdocs.yml` and running `make docs` again. #### Updating the documentation[¶](#updating-the-documentation "Permanent link") We push a new version of the documentation with each minor release, and we push to a `dev` path with each commit to `main`. If you're updating the documentation out of cycle with a minor release and want your changes to be reflected on `latest`, do the following: 1. Open a PR against `main` with your docs changes 2. Once the PR is merged, checkout the `docs-update` branch. This branch should be up to date with the latest patch release. For example, if the latest release is `v2.9.2`, you should make sure `docs-update` is up to date with the `v2.9.2` tag. 3. Checkout a new branch from `docs-update` and cherry-pick your changes onto this branch. 4. Push your changes and open a PR against `docs-update`. 5. Once the PR is merged, the new docs will be built and deployed. Note Maintainer shortcut - as a maintainer, you can skip the second PR and just cherry pick directly onto the `docs-update` branch. ### Commit and push your changes[¶](#commit-and-push-your-changes "Permanent link") Commit your changes, push your branch to GitHub, and create a pull request. Please follow the pull request template and fill in as much information as possible. Link to any relevant issues and include a description of your changes. When your pull request is ready for review, add a comment with the message "please review" and we'll take a look as soon as we can. Documentation style[¶](#documentation-style "Permanent link") -------------------------------------------------------------- Documentation is written in Markdown and built using [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) . API documentation is build from docstrings using [mkdocstrings](https://mkdocstrings.github.io/) . ### Code documentation[¶](#code-documentation "Permanent link") When contributing to Pydantic, please make sure that all code is well documented. The following should be documented using properly formatted docstrings: * Modules * Class definitions * Function definitions * Module-level variables Pydantic uses [Google-style docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) formatted according to [PEP 257](https://www.python.org/dev/peps/pep-0257/) guidelines. (See [Example Google Style Python Docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) for further examples.) [pydocstyle](https://www.pydocstyle.org/en/stable/index.html) is used for linting docstrings. You can run `make format` to check your docstrings. Where this is a conflict between Google-style docstrings and pydocstyle linting, follow the pydocstyle linting hints. Class attributes and function arguments should be documented in the format "name: description." When applicable, a return type should be documented with just a description. Types are inferred from the signature. `class Foo: """A class docstring. Attributes: bar: A description of bar. Defaults to "bar". """ bar: str = 'bar'` ``def bar(self, baz: int) -> str: """A function docstring. Args: baz: A description of `baz`. Returns: A description of the return value. """ return 'bar'`` You may include example code in docstrings. This code should be complete, self-contained, and runnable. Docstring examples are tested, so make sure they are correct and complete. See [`FieldInfo.from_annotated_attribute`](../api/fields/#pydantic.fields.FieldInfo.from_annotated_attribute) for an example. Class and instance attributes Class attributes should be documented in the class docstring. Instance attributes should be documented as "Args" in the `__init__` docstring. ### Documentation Style[¶](#documentation-style_1 "Permanent link") In general, documentation should be written in a friendly, approachable style. It should be easy to read and understand, and should be as concise as possible while still being complete. Code examples are encouraged, but should be kept short and simple. However, every code example should be complete, self-contained, and runnable. (If you're not sure how to do this, ask for help!) We prefer print output to naked asserts, but if you're testing something that doesn't have a useful print output, asserts are fine. Pydantic's unit test will test all code examples in the documentation, so it's important that they are correct and complete. When adding a new code example, use the following to test examples and update their formatting and output: `# Run tests and update code examples pytest tests/test_docs.py --update-examples` Debugging Python and Rust[¶](#debugging-python-and-rust "Permanent link") -------------------------------------------------------------------------- If you're working with `pydantic` and `pydantic-core`, you might find it helpful to debug Python and Rust code together. Here's a quick guide on how to do that. This tutorial is done in VSCode, but you can use similar steps in other IDEs. Badges[¶](#badges "Permanent link") ------------------------------------ [![Pydantic v1](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v1.json)](https://pydantic.dev) [![Pydantic v2](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json)](https://pydantic.dev) Pydantic has a badge that you can use to show that your project uses Pydantic. You can use this badge in your `README.md`: ### With Markdown[¶](#with-markdown "Permanent link") `[![Pydantic v1](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v1.json)](https://pydantic.dev) [![Pydantic v2](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json)](https://pydantic.dev)` ### With reStructuredText[¶](#with-restructuredtext "Permanent link") `.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v1.json :target: https://pydantic.dev :alt: Pydantic .. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json :target: https://pydantic.dev :alt: Pydantic` ### With HTML[¶](#with-html "Permanent link") `Pydantic Version 1 Pydantic Version 2` Adding your library as part of Pydantic's third party test suite[¶](#adding-your-library-as-part-of-pydantics-third-party-test-suite "Permanent link") ------------------------------------------------------------------------------------------------------------------------------------------------------- To be able to identify regressions early during development, Pydantic runs tests on various third-party projects using Pydantic. We consider adding support for testing new open source projects (that rely heavily on Pydantic) if your said project matches some of the following criteria: * The project is actively maintained. * The project makes use of Pydantic internals (e.g. relying on the [`BaseModel`](../api/base_model/#pydantic.BaseModel) metaclass, typing utilities). * The project is popular enough (although small projects can still be included depending on how Pydantic is being used). * The project CI is simple enough to be ported into Pydantic's testing workflow. If your project meets some of these criteria, you can [open feature request](https://github.com/pydantic/pydantic/issues/new?assignees=&labels=feature+request&projects=&template=feature_request.yml) to discuss the inclusion of your project. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Installation - Pydantic Installation ============ Installation is as simple as: pipuv `pip install pydantic` `uv add pydantic` Pydantic has a few dependencies: * [`pydantic-core`](https://pypi.org/project/pydantic-core/) : Core validation logic for Pydantic written in Rust. * [`typing-extensions`](https://pypi.org/project/typing-extensions/) : Backport of the standard library [typing](https://docs.python.org/3/library/typing.html#module-typing) module. * [`annotated-types`](https://pypi.org/project/annotated-types/) : Reusable constraint types to use with [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) . If you've got Python 3.9+ and `pip` installed, you're good to go. Pydantic is also available on [conda](https://www.anaconda.com) under the [conda-forge](https://conda-forge.org) channel: `conda install pydantic -c conda-forge` Optional dependencies[¶](#optional-dependencies "Permanent link") ------------------------------------------------------------------ Pydantic has the following optional dependencies: * `email`: Email validation provided by the [email-validator](https://pypi.org/project/email-validator/) package. * `timezone`: Fallback IANA time zone database provided by the [tzdata](https://pypi.org/project/tzdata/) package. To install optional dependencies along with Pydantic: pipuv ``# with the `email` extra: pip install 'pydantic[email]' # or with `email` and `timezone` extras: pip install 'pydantic[email,timezone]'`` ``# with the `email` extra: uv add 'pydantic[email]' # or with `email` and `timezone` extras: uv add 'pydantic[email,timezone]'`` Of course, you can also install requirements manually with `pip install email-validator tzdata`. Install from repository[¶](#install-from-repository "Permanent link") ---------------------------------------------------------------------- And if you prefer to install Pydantic directly from the repository: pipuv ``pip install 'git+https://github.com/pydantic/pydantic@main' # or with `email` and `timezone` extras: pip install 'git+https://github.com/pydantic/pydantic@main#egg=pydantic[email,timezone]'`` ``uv add 'git+https://github.com/pydantic/pydantic@main' # or with `email` and `timezone` extras: uv add 'git+https://github.com/pydantic/pydantic@main#egg=pydantic[email,timezone]'`` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Aliases - Pydantic Aliases ======= Support for alias configurations. AliasPath `dataclass` [¶](#pydantic.aliases.AliasPath "Permanent link") ------------------------------------------------------------------------ `AliasPath(first_arg: [str](https://docs.python.org/3/library/stdtypes.html#str) , *args: [str](https://docs.python.org/3/library/stdtypes.html#str) | [int](https://docs.python.org/3/library/functions.html#int) )` Usage Documentation [`AliasPath` and `AliasChoices`](../../concepts/alias/#aliaspath-and-aliaschoices) A data class used by `validation_alias` as a convenience to create aliases. Attributes: | Name | Type | Description | | --- | --- | --- | | `path` | `[list](https://docs.python.org/3/glossary.html#term-list) [[int](https://docs.python.org/3/library/functions.html#int) \| [str](https://docs.python.org/3/library/stdtypes.html#str) ]` | A list of string or integer aliases. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 28
29 | `def __init__(self, first_arg: str, *args: str \| int) -> None: self.path = [first_arg] + list(args)` | ### convert\_to\_aliases [¶](#pydantic.aliases.AliasPath.convert_to_aliases "Permanent link") `convert_to_aliases() -> [list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) | [int](https://docs.python.org/3/library/functions.html#int) ]` Converts arguments to a list of string or integer aliases. Returns: | Type | Description | | --- | --- | | `[list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) \| [int](https://docs.python.org/3/library/functions.html#int) ]` | The list of aliases. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 31
32
33
34
35
36
37 | `def convert_to_aliases(self) -> list[str \| int]: """Converts arguments to a list of string or integer aliases. Returns: The list of aliases. """ return self.path` | ### search\_dict\_for\_path [¶](#pydantic.aliases.AliasPath.search_dict_for_path "Permanent link") `search_dict_for_path(d: [dict](https://docs.python.org/3/reference/expressions.html#dict) ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Searches a dictionary for the path specified by the alias. Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The value at the specified path, or `PydanticUndefined` if the path is not found. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 | ``def search_dict_for_path(self, d: dict) -> Any: """Searches a dictionary for the path specified by the alias. Returns: The value at the specified path, or `PydanticUndefined` if the path is not found. """ v = d for k in self.path: if isinstance(v, str): # disallow indexing into a str, like for AliasPath('x', 0) and x='abc' return PydanticUndefined try: v = v[k] except (KeyError, IndexError, TypeError): return PydanticUndefined return v`` | AliasChoices `dataclass` [¶](#pydantic.aliases.AliasChoices "Permanent link") ------------------------------------------------------------------------------ `AliasChoices( first_choice: [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") , *choices: [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") )` Usage Documentation [`AliasPath` and `AliasChoices`](../../concepts/alias/#aliaspath-and-aliaschoices) A data class used by `validation_alias` as a convenience to create aliases. Attributes: | Name | Type | Description | | --- | --- | --- | | `choices` | `[list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) \| [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") ]` | A list containing a string or `AliasPath`. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 70
71 | `def __init__(self, first_choice: str \| AliasPath, *choices: str \| AliasPath) -> None: self.choices = [first_choice] + list(choices)` | ### convert\_to\_aliases [¶](#pydantic.aliases.AliasChoices.convert_to_aliases "Permanent link") `convert_to_aliases() -> [list](https://docs.python.org/3/glossary.html#term-list) [[list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) | [int](https://docs.python.org/3/library/functions.html#int) ]]` Converts arguments to a list of lists containing string or integer aliases. Returns: | Type | Description | | --- | --- | | `[list](https://docs.python.org/3/glossary.html#term-list) [[list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) \| [int](https://docs.python.org/3/library/functions.html#int) ]]` | The list of aliases. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 73
74
75
76
77
78
79
80
81
82
83
84
85 | `def convert_to_aliases(self) -> list[list[str \| int]]: """Converts arguments to a list of lists containing string or integer aliases. Returns: The list of aliases. """ aliases: list[list[str \| int]] = [] for c in self.choices: if isinstance(c, AliasPath): aliases.append(c.convert_to_aliases()) else: aliases.append([c]) return aliases` | AliasGenerator `dataclass` [¶](#pydantic.aliases.AliasGenerator "Permanent link") ---------------------------------------------------------------------------------- `AliasGenerator( alias: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = None, validation_alias: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") ] | None ) = None, serialization_alias: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = None, )` Usage Documentation [Using an `AliasGenerator`](../../concepts/alias/#using-an-aliasgenerator) A data class used by `alias_generator` as a convenience to create various aliases. Attributes: | Name | Type | Description | | --- | --- | --- | | `alias` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns an alias for it. | | `validation_alias` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) \| [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") \| [AliasChoices](#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") ] \| None` | A callable that takes a field name and returns a validation alias for it. | | `serialization_alias` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns a serialization alias for it. | ### generate\_aliases [¶](#pydantic.aliases.AliasGenerator.generate_aliases "Permanent link") `generate_aliases( field_name: [str](https://docs.python.org/3/library/stdtypes.html#str) , ) -> [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [ [str](https://docs.python.org/3/library/stdtypes.html#str) | None, [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None, [str](https://docs.python.org/3/library/stdtypes.html#str) | None, ]` Generate `alias`, `validation_alias`, and `serialization_alias` for a field. Returns: | Type | Description | | --- | --- | | `[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) \| None, [str](https://docs.python.org/3/library/stdtypes.html#str) \| [AliasPath](#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") \| [AliasChoices](#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") \| None, [str](https://docs.python.org/3/library/stdtypes.html#str) \| None]` | A tuple of three aliases - validation, alias, and serialization. | Source code in `pydantic/aliases.py` | | | | --- | --- | | 125
126
127
128
129
130
131
132
133
134
135 | ``def generate_aliases(self, field_name: str) -> tuple[str \| None, str \| AliasPath \| AliasChoices \| None, str \| None]: """Generate `alias`, `validation_alias`, and `serialization_alias` for a field. Returns: A tuple of three aliases - validation, alias, and serialization. """ alias = self._generate_alias('alias', (str,), field_name) validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name) serialization_alias = self._generate_alias('serialization_alias', (str,), field_name) return alias, validation_alias, serialization_alias # type: ignore`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Pydantic People - Pydantic Pydantic People[¶](#pydantic-people "Permanent link") ====================================================== Pydantic has an amazing community of contributors, reviewers, and experts that help propel the project forward. Here, we celebrate those people and their contributions. Maintainers[¶](#maintainers "Permanent link") ---------------------------------------------- These are the current maintainers of the Pydantic repository. Feel free to tag us if you have questions, review requests, or feature requests for which you'd like feedback! [![](https://avatars.githubusercontent.com/u/3122442?u=f387fc2dbc0c681f23e80e2ad705790fafcec9a2&v=4)\ \ @hramezani](https://github.com/hramezani) [![](https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4)\ \ @adriangb](https://github.com/adriangb) [![](https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4)\ \ @Viicos](https://github.com/Viicos) [![](https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4)\ \ @dmontagu](https://github.com/dmontagu) [![](https://avatars.githubusercontent.com/u/1939362?u=b4b48981c3a097daaad16c4c5417aa7a3e5e32d9&v=4)\ \ @davidhewitt](https://github.com/davidhewitt) [![](https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4)\ \ @Kludex](https://github.com/Kludex) [![](https://avatars.githubusercontent.com/u/54324534?u=3a4ffd00a8270b607922250d3a2d9c9af38b9cf9&v=4)\ \ @sydney-runkle](https://github.com/sydney-runkle) [![](https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4)\ \ @samuelcolvin](https://github.com/samuelcolvin) [![](https://avatars.githubusercontent.com/u/3627481?u=9bb2e0cf1c5ef3d0609d2e639a135b7b4ca8b463&v=4)\ \ @alexmojaki](https://github.com/alexmojaki) Experts[¶](#experts "Permanent link") -------------------------------------- These are the users that have helped others the most with questions in GitHub through _all time_. [![](https://avatars.githubusercontent.com/u/18406791?u=4853940cf5eeffb5bbb9ba06ad862f28bc68d69e&v=4)\ \ @PrettyWood](https://github.com/PrettyWood) Questions replied: 143 [![](https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4)\ \ @uriyyo](https://github.com/uriyyo) Questions replied: 96 [![](https://avatars.githubusercontent.com/u/2184855?u=5670768b7efda993c4887d91df3cf330dc7bc9de&v=4)\ \ @lesnik512](https://github.com/lesnik512) Questions replied: 21 [![](https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4)\ \ @harunyasar](https://github.com/harunyasar) Questions replied: 17 [![](https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4)\ \ @nymous](https://github.com/nymous) Questions replied: 13 [![](https://avatars.githubusercontent.com/u/40807730?v=4)\ \ @ybressler](https://github.com/ybressler) Questions replied: None ### Most active users last month[¶](#most-active-users-last-month "Permanent link") These are the users that have helped others the most with questions in GitHub during the last month. Top contributors[¶](#top-contributors "Permanent link") -------------------------------------------------------- These are the users that have created the most pull requests that have been _merged_. [![](https://avatars.githubusercontent.com/u/18406791?u=4853940cf5eeffb5bbb9ba06ad862f28bc68d69e&v=4)\ \ @PrettyWood](https://github.com/PrettyWood) Contributions: 122 [![](https://avatars.githubusercontent.com/in/2141?v=4)\ \ @dependabot-preview](https://github.com/apps/dependabot-preview) Contributions: 75 [![](https://avatars.githubusercontent.com/u/370316?u=eb206070cfe47f242d5fcea2e6c7514f4d0f27f5&v=4)\ \ @tpdorsey](https://github.com/tpdorsey) Contributions: 71 [![](https://avatars.githubusercontent.com/u/38705?v=4)\ \ @lig](https://github.com/lig) Contributions: 49 [![](https://avatars.githubusercontent.com/u/16239342?u=8454ae029661131445080f023e1efccc29166485&v=4)\ \ @pyup-bot](https://github.com/pyup-bot) Contributions: 46 [![](https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4)\ \ @tiangolo](https://github.com/tiangolo) Contributions: 22 [![](https://avatars.githubusercontent.com/u/36469655?u=f67d8fa6d67d35d2f5ebd5b15e24efeb41036fd3&v=4)\ \ @Bobronium](https://github.com/Bobronium) Contributions: 19 [![](https://avatars.githubusercontent.com/u/1087619?u=cd78c4f602bf9f9667277dd0af9302a7fe9dd75a&v=4)\ \ @Gr1N](https://github.com/Gr1N) Contributions: 17 [![](https://avatars.githubusercontent.com/u/1271289?u=b83b0a82b2c95990d93cefbeb8f548d9f2f090c2&v=4)\ \ @misrasaurabh1](https://github.com/misrasaurabh1) Contributions: 16 [![](https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4)\ \ @uriyyo](https://github.com/uriyyo) Contributions: 15 [![](https://avatars.githubusercontent.com/u/6400248?u=2b30c6675f888c2e47640aed2f1c1a956baae224&v=4)\ \ @pilosus](https://github.com/pilosus) Contributions: 12 [![](https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4)\ \ @yezz123](https://github.com/yezz123) Contributions: 12 [![](https://avatars.githubusercontent.com/u/89458301?u=75f53e971fcba3ff61836c389505a420bddd865c&v=4)\ \ @kc0506](https://github.com/kc0506) Contributions: 12 [![](https://avatars.githubusercontent.com/u/1148665?u=b69e6fe797302f025a2d125e377e27f8ea0b8058&v=4)\ \ @StephenBrown2](https://github.com/StephenBrown2) Contributions: 10 [![](https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4)\ \ @koxudaxi](https://github.com/koxudaxi) Contributions: 9 [![](https://avatars.githubusercontent.com/u/30130371?v=4)\ \ @cdce8p](https://github.com/cdce8p) Contributions: 9 [![](https://avatars.githubusercontent.com/u/19784933?v=4)\ \ @aminalaee](https://github.com/aminalaee) Contributions: 8 [![](https://avatars.githubusercontent.com/u/70970900?u=573a3175906348e0d1529104d56b391e93ca0250&v=4)\ \ @NeevCohen](https://github.com/NeevCohen) Contributions: 8 [![](https://avatars.githubusercontent.com/u/31134424?u=e8afd95a97b5556c467d1be27788950e67378ef1&v=4)\ \ @layday](https://github.com/layday) Contributions: 7 [![](https://avatars.githubusercontent.com/u/1049817?u=b42e1148d23ea9039b325975bbea3ff8c5b4e3ec&v=4)\ \ @daviskirk](https://github.com/daviskirk) Contributions: 7 [![](https://avatars.githubusercontent.com/u/1609449?u=922abf0524b47739b37095e553c99488814b05db&v=4)\ \ @tlambert03](https://github.com/tlambert03) Contributions: 7 [![](https://avatars.githubusercontent.com/u/1769841?u=44e83d7974f0ab5c431340f1669d98f781594980&v=4)\ \ @dgasmith](https://github.com/dgasmith) Contributions: 6 [![](https://avatars.githubusercontent.com/u/202696?v=4)\ \ @Atheuz](https://github.com/Atheuz) Contributions: 6 [![](https://avatars.githubusercontent.com/u/16639270?u=faa71bcfb3273a32cd81711a56998e115bca7fcc&v=4)\ \ @AdolfoVillalobos](https://github.com/AdolfoVillalobos) Contributions: 6 [![](https://avatars.githubusercontent.com/u/6339494?u=893876f31ce65fa8ad8cfcc592392a77f0f8af38&v=4)\ \ @nuno-andre](https://github.com/nuno-andre) Contributions: 5 [![](https://avatars.githubusercontent.com/u/9677399?u=386c330f212ce467ce7119d9615c75d0e9b9f1ce&v=4)\ \ @ofek](https://github.com/ofek) Contributions: 5 [![](https://avatars.githubusercontent.com/u/1734544?v=4)\ \ @hmvp](https://github.com/hmvp) Contributions: 4 [![](https://avatars.githubusercontent.com/u/24581770?v=4)\ \ @retnikt](https://github.com/retnikt) Contributions: 4 [![](https://avatars.githubusercontent.com/u/197540?v=4)\ \ @therefromhere](https://github.com/therefromhere) Contributions: 4 [![](https://avatars.githubusercontent.com/u/10811879?u=c0cfe7f7be82474d0deb2ba27601ec96f4f43515&v=4)\ \ @JeanArhancet](https://github.com/JeanArhancet) Contributions: 4 [![](https://avatars.githubusercontent.com/u/164513?v=4)\ \ @commonism](https://github.com/commonism) Contributions: 4 [![](https://avatars.githubusercontent.com/u/12939780?v=4)\ \ @MarkusSintonen](https://github.com/MarkusSintonen) Contributions: 4 [![](https://avatars.githubusercontent.com/u/59469646?u=86d6a20768cc4cc65622eafd86672147321bd8f8&v=4)\ \ @JensHeinrich](https://github.com/JensHeinrich) Contributions: 4 [![](https://avatars.githubusercontent.com/u/110765?u=7386b9cb55c1973a510d2785832424bc80e7c265&v=4)\ \ @mgorny](https://github.com/mgorny) Contributions: 4 [![](https://avatars.githubusercontent.com/u/25489980?u=1e9b5cbbbb1516fbea6da00429e4eef0ef79e4e6&v=4)\ \ @ornariece](https://github.com/ornariece) Contributions: 4 [![](https://avatars.githubusercontent.com/u/166007669?u=cd5df427a775972595777471436c673e94e03a1f&v=4)\ \ @rx-dwoodward](https://github.com/rx-dwoodward) Contributions: 4 [![](https://avatars.githubusercontent.com/u/45747761?u=c1515d2ccf4877c0b64b5ea5a8c51631affe35de&v=4)\ \ @dAIsySHEng1](https://github.com/dAIsySHEng1) Contributions: 4 [![](https://avatars.githubusercontent.com/u/9328433?u=8546519cb04223cd878285d72c27850b5f3f0882&v=4)\ \ @mschoettle](https://github.com/mschoettle) Contributions: 4 Top Reviewers[¶](#top-reviewers "Permanent link") -------------------------------------------------- These are the users that have reviewed the most Pull Requests from others, assisting with code quality, documentation, bug fixes, feature requests, etc. [![](https://avatars.githubusercontent.com/u/18406791?u=4853940cf5eeffb5bbb9ba06ad862f28bc68d69e&v=4)\ \ @PrettyWood](https://github.com/PrettyWood) Reviews: 211 [![](https://avatars.githubusercontent.com/u/38705?v=4)\ \ @lig](https://github.com/lig) Reviews: 103 [![](https://avatars.githubusercontent.com/u/370316?u=eb206070cfe47f242d5fcea2e6c7514f4d0f27f5&v=4)\ \ @tpdorsey](https://github.com/tpdorsey) Reviews: 77 [![](https://avatars.githubusercontent.com/in/718456?v=4)\ \ @hyperlint-ai](https://github.com/apps/hyperlint-ai) Reviews: 56 [![](https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4)\ \ @tiangolo](https://github.com/tiangolo) Reviews: 44 [![](https://avatars.githubusercontent.com/u/36469655?u=f67d8fa6d67d35d2f5ebd5b15e24efeb41036fd3&v=4)\ \ @Bobronium](https://github.com/Bobronium) Reviews: 27 [![](https://avatars.githubusercontent.com/u/1087619?u=cd78c4f602bf9f9667277dd0af9302a7fe9dd75a&v=4)\ \ @Gr1N](https://github.com/Gr1N) Reviews: 17 [![](https://avatars.githubusercontent.com/u/1148665?u=b69e6fe797302f025a2d125e377e27f8ea0b8058&v=4)\ \ @StephenBrown2](https://github.com/StephenBrown2) Reviews: 17 [![](https://avatars.githubusercontent.com/u/12939780?v=4)\ \ @MarkusSintonen](https://github.com/MarkusSintonen) Reviews: 16 [![](https://avatars.githubusercontent.com/u/40807730?u=b417e3cea56fd0f67983006108f6a1a83d4652a0&v=4)\ \ @ybressler](https://github.com/ybressler) Reviews: 15 [![](https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4)\ \ @uriyyo](https://github.com/uriyyo) Reviews: 11 [![](https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4)\ \ @koxudaxi](https://github.com/koxudaxi) Reviews: 10 [![](https://avatars.githubusercontent.com/u/1049817?u=b42e1148d23ea9039b325975bbea3ff8c5b4e3ec&v=4)\ \ @daviskirk](https://github.com/daviskirk) Reviews: 10 [![](https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4)\ \ @yezz123](https://github.com/yezz123) Reviews: 10 [![](https://avatars.githubusercontent.com/u/12229877?u=abc44dbce4bb3eca2def638bd0d4ab4cfef91b74&v=4)\ \ @Zac-HD](https://github.com/Zac-HD) Reviews: 8 [![](https://avatars.githubusercontent.com/u/31134424?u=e8afd95a97b5556c467d1be27788950e67378ef1&v=4)\ \ @layday](https://github.com/layday) Reviews: 7 [![](https://avatars.githubusercontent.com/u/89458301?u=75f53e971fcba3ff61836c389505a420bddd865c&v=4)\ \ @kc0506](https://github.com/kc0506) Reviews: 7 [![](https://avatars.githubusercontent.com/u/6400248?u=2b30c6675f888c2e47640aed2f1c1a956baae224&v=4)\ \ @pilosus](https://github.com/pilosus) Reviews: 6 [![](https://avatars.githubusercontent.com/u/13108583?u=0d34d39c0628091596c9d5ebb4e802009e8c4aca&v=4)\ \ @Kilo59](https://github.com/Kilo59) Reviews: 6 [![](https://avatars.githubusercontent.com/u/10811879?u=c0cfe7f7be82474d0deb2ba27601ec96f4f43515&v=4)\ \ @JeanArhancet](https://github.com/JeanArhancet) Reviews: 6 [![](https://avatars.githubusercontent.com/u/1609449?u=922abf0524b47739b37095e553c99488814b05db&v=4)\ \ @tlambert03](https://github.com/tlambert03) Reviews: 5 [![](https://avatars.githubusercontent.com/u/537700?u=7b64bd12eda862fbf72228495aada9c470df7a90&v=4)\ \ @christianbundy](https://github.com/christianbundy) Reviews: 5 [![](https://avatars.githubusercontent.com/u/16438204?u=f700f440b89e715795c3bc091800b8d3f39c58d9&v=4)\ \ @nix010](https://github.com/nix010) Reviews: 5 [![](https://avatars.githubusercontent.com/u/413772?v=4)\ \ @graingert](https://github.com/graingert) Reviews: 4 [![](https://avatars.githubusercontent.com/u/1734544?v=4)\ \ @hmvp](https://github.com/hmvp) Reviews: 4 [![](https://avatars.githubusercontent.com/u/5042313?u=8917c345dcb528733073ff1ce8a512e33f548512&v=4)\ \ @wozniakty](https://github.com/wozniakty) Reviews: 4 [![](https://avatars.githubusercontent.com/u/6339494?u=893876f31ce65fa8ad8cfcc592392a77f0f8af38&v=4)\ \ @nuno-andre](https://github.com/nuno-andre) Reviews: 4 [![](https://avatars.githubusercontent.com/u/2099618?u=a9899c1fea247d500e5368a1157a392bcd82e81d&v=4)\ \ @antdking](https://github.com/antdking) Reviews: 4 [![](https://avatars.githubusercontent.com/u/662249?u=15313dec91bae789685e4abb3c2152251de41948&v=4)\ \ @dimaqq](https://github.com/dimaqq) Reviews: 4 [![](https://avatars.githubusercontent.com/u/59469646?u=86d6a20768cc4cc65622eafd86672147321bd8f8&v=4)\ \ @JensHeinrich](https://github.com/JensHeinrich) Reviews: 4 About the data[¶](#about-the-data "Permanent link") ---------------------------------------------------- The data displayed above is calculated monthly via the Github GraphQL API. The source code for this script is located [here](https://github.com/pydantic/pydantic/tree/main/.github/actions/people/people.py) . Many thanks to [Sebastián Ramírez](https://github.com/tiangolo) for the script from which we based this logic. Depending on changing conditions, the thresholds for the different categories of contributors may change in the future. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Annotated Handlers - Pydantic Annotated Handlers ================== Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`. GetJsonSchemaHandler [¶](#pydantic.annotated_handlers.GetJsonSchemaHandler "Permanent link") --------------------------------------------------------------------------------------------- Handler to call into the next JSON schema generation function. Attributes: | Name | Type | Description | | --- | --- | --- | | `mode` | `[JsonSchemaMode](../json_schema/#pydantic.json_schema.JsonSchemaMode "pydantic.json_schema.JsonSchemaMode") ` | Json schema mode, can be `validation` or `serialization`. | ### resolve\_ref\_schema [¶](#pydantic.annotated_handlers.GetJsonSchemaHandler.resolve_ref_schema "Permanent link") `resolve_ref_schema( maybe_ref_json_schema: [JsonSchemaValue](../json_schema/#pydantic.json_schema.JsonSchemaValue "pydantic.json_schema.JsonSchemaValue") , ) -> [JsonSchemaValue](../json_schema/#pydantic.json_schema.JsonSchemaValue "pydantic.json_schema.JsonSchemaValue")` Get the real schema for a `{"$ref": ...}` schema. If the schema given is not a `$ref` schema, it will be returned as is. This means you don't have to check before calling this function. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `maybe_ref_json_schema` | `[JsonSchemaValue](../json_schema/#pydantic.json_schema.JsonSchemaValue "pydantic.json_schema.JsonSchemaValue") ` | A JsonSchemaValue which may be a `$ref` schema. | _required_ | Raises: | Type | Description | | --- | --- | | `[LookupError](https://docs.python.org/3/library/exceptions.html#LookupError) ` | If the ref is not found. | Returns: | Name | Type | Description | | --- | --- | --- | | `JsonSchemaValue` | `[JsonSchemaValue](../json_schema/#pydantic.json_schema.JsonSchemaValue "pydantic.json_schema.JsonSchemaValue") ` | A JsonSchemaValue that has no `$ref`. | Source code in `pydantic/annotated_handlers.py` | | | | --- | --- | | 49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 | ``def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue: """Get the real schema for a `{"$ref": ...}` schema. If the schema given is not a `$ref` schema, it will be returned as is. This means you don't have to check before calling this function. Args: maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema. Raises: LookupError: If the ref is not found. Returns: JsonSchemaValue: A JsonSchemaValue that has no `$ref`. """ raise NotImplementedError`` | GetCoreSchemaHandler [¶](#pydantic.annotated_handlers.GetCoreSchemaHandler "Permanent link") --------------------------------------------------------------------------------------------- Handler to call into the next CoreSchema schema generation function. ### field\_name `property` [¶](#pydantic.annotated_handlers.GetCoreSchemaHandler.field_name "Permanent link") `field_name: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` Get the name of the closest field to this validator. ### generate\_schema [¶](#pydantic.annotated_handlers.GetCoreSchemaHandler.generate_schema "Permanent link") `generate_schema(source_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> CoreSchema` Generate a schema unrelated to the current context. Use this function if e.g. you are handling schema generation for a sequence and want to generate a schema for its items. Otherwise, you may end up doing something like applying a `min_length` constraint that was intended for the sequence itself to its items! Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `source_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The input type. | _required_ | Returns: | Name | Type | Description | | --- | --- | --- | | `CoreSchema` | `CoreSchema` | The `pydantic-core` CoreSchema generated. | Source code in `pydantic/annotated_handlers.py` | | | | --- | --- | | 84
85
86
87
88
89
90
91
92
93
94
95
96
97 | ``def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema: """Generate a schema unrelated to the current context. Use this function if e.g. you are handling schema generation for a sequence and want to generate a schema for its items. Otherwise, you may end up doing something like applying a `min_length` constraint that was intended for the sequence itself to its items! Args: source_type: The input type. Returns: CoreSchema: The `pydantic-core` CoreSchema generated. """ raise NotImplementedError`` | ### resolve\_ref\_schema [¶](#pydantic.annotated_handlers.GetCoreSchemaHandler.resolve_ref_schema "Permanent link") `resolve_ref_schema( maybe_ref_schema: CoreSchema, ) -> CoreSchema` Get the real schema for a `definition-ref` schema. If the schema given is not a `definition-ref` schema, it will be returned as is. This means you don't have to check before calling this function. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `maybe_ref_schema` | `CoreSchema` | A `CoreSchema`, `ref`\-based or not. | _required_ | Raises: | Type | Description | | --- | --- | | `[LookupError](https://docs.python.org/3/library/exceptions.html#LookupError) ` | If the `ref` is not found. | Returns: | Type | Description | | --- | --- | | `CoreSchema` | A concrete `CoreSchema`. | Source code in `pydantic/annotated_handlers.py` | | | | --- | --- | | 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113 | ``def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema: """Get the real schema for a `definition-ref` schema. If the schema given is not a `definition-ref` schema, it will be returned as is. This means you don't have to check before calling this function. Args: maybe_ref_schema: A `CoreSchema`, `ref`-based or not. Raises: LookupError: If the `ref` is not found. Returns: A concrete `CoreSchema`. """ raise NotImplementedError`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Help with Pydantic - Pydantic Getting help with Pydantic[¶](#getting-help-with-pydantic "Permanent link") ============================================================================ If you need help getting started with Pydantic or with advanced usage, the following sources may be useful. Usage Documentation[¶](#usage-documentation "Permanent link") -------------------------------------------------------------- The [usage documentation](../concepts/models/) is the most complete guide on how to use Pydantic. API Documentation[¶](#api-documentation "Permanent link") ---------------------------------------------------------- The [API documentation](../api/base_model/) give reference docs for all public Pydantic APIs. GitHub Discussions[¶](#github-discussions "Permanent link") ------------------------------------------------------------ [GitHub discussions](https://github.com/pydantic/pydantic/discussions) are useful for asking questions, your question and the answer will help everyone. Stack Overflow[¶](#stack-overflow "Permanent link") ---------------------------------------------------- Use the [`pydantic`](https://stackoverflow.com/questions/tagged/pydantic) tag on Stack Overflow to ask questions, note this is not always monitored by the core Pydantic team. YouTube[¶](#youtube "Permanent link") -------------------------------------- Youtube as lots of useful [videos on Pydantic](https://www.youtube.com/results?search_query=pydantic) . In particular Marcelo Trylesinski's video ["Pydantic V1 to V2 - The Migration"](https://youtu.be/sD_xpYl4fPU) has helped people a lot when migrating from Pydantic V1 to V2. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Changelog - Pydantic Changelog ========= v2.11.3 (2025-04-08)[¶](#v2113-2025-04-08 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.3) ### What's Changed[¶](#whats-changed "Permanent link") #### Packaging[¶](#packaging "Permanent link") * Update V1 copy to v1.10.21 by [@Viicos](https://github.com/Viicos) in [#11706](https://github.com/pydantic/pydantic/pull/11706) #### Fixes[¶](#fixes "Permanent link") * Preserve field description when rebuilding model fields by [@Viicos](https://github.com/Viicos) in [#11698](https://github.com/pydantic/pydantic/pull/11698) v2.11.2 (2025-04-03)[¶](#v2112-2025-04-03 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.2) ### What's Changed[¶](#whats-changed_1 "Permanent link") #### Fixes[¶](#fixes_1 "Permanent link") * Bump `pydantic-core` to v2.33.1 by [@Viicos](https://github.com/Viicos) in [#11678](https://github.com/pydantic/pydantic/pull/11678) * Make sure `__pydantic_private__` exists before setting private attributes by [@Viicos](https://github.com/Viicos) in [#11666](https://github.com/pydantic/pydantic/pull/11666) * Do not override `FieldInfo._complete` when using field from parent class by [@Viicos](https://github.com/Viicos) in [#11668](https://github.com/pydantic/pydantic/pull/11668) * Provide the available definitions when applying discriminated unions by [@Viicos](https://github.com/Viicos) in [#11670](https://github.com/pydantic/pydantic/pull/11670) * Do not expand root type in the mypy plugin for variables by [@Viicos](https://github.com/Viicos) in [#11676](https://github.com/pydantic/pydantic/pull/11676) * Mention the attribute name in model fields deprecation message by [@Viicos](https://github.com/Viicos) in [#11674](https://github.com/pydantic/pydantic/pull/11674) * Properly validate parameterized mappings by [@Viicos](https://github.com/Viicos) in [#11658](https://github.com/pydantic/pydantic/pull/11658) v2.11.1 (2025-03-28)[¶](#v2111-2025-03-28 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.1) ### What's Changed[¶](#whats-changed_2 "Permanent link") #### Fixes[¶](#fixes_2 "Permanent link") * Do not override `'definitions-ref'` schemas containing serialization schemas or metadata by [@Viicos](https://github.com/Viicos) in [#11644](https://github.com/pydantic/pydantic/pull/11644) v2.11.0 (2025-03-27)[¶](#v2110-2025-03-27 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0) ### What's Changed[¶](#whats-changed_3 "Permanent link") Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general). See the [blog post](https://pydantic.dev/articles/pydantic-v2-11-release) for more details. #### Packaging[¶](#packaging_1 "Permanent link") * Bump `pydantic-core` to v2.33.0 by [@Viicos](https://github.com/Viicos) in [#11631](https://github.com/pydantic/pydantic/pull/11631) #### New Features[¶](#new-features "Permanent link") * Add `encoded_string()` method to the URL types by [@YassinNouh21](https://github.com/YassinNouh21) in [#11580](https://github.com/pydantic/pydantic/pull/11580) * Add support for `defer_build` with `@validate_call` decorator by [@Viicos](https://github.com/Viicos) in [#11584](https://github.com/pydantic/pydantic/pull/11584) * Allow `@with_config` decorator to be used with keyword arguments by [@Viicos](https://github.com/Viicos) in [#11608](https://github.com/pydantic/pydantic/pull/11608) * Simplify customization of default value inclusion in JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#11634](https://github.com/pydantic/pydantic/pull/11634) * Add `generate_arguments_schema()` function by [@Viicos](https://github.com/Viicos) in [#11572](https://github.com/pydantic/pydantic/pull/11572) #### Fixes[¶](#fixes_3 "Permanent link") * Allow generic typed dictionaries to be used for unpacked variadic keyword parameters by [@Viicos](https://github.com/Viicos) in [#11571](https://github.com/pydantic/pydantic/pull/11571) * Fix runtime error when computing model string representation involving cached properties and self-referenced models by [@Viicos](https://github.com/Viicos) in [#11579](https://github.com/pydantic/pydantic/pull/11579) * Preserve other steps when using the ellipsis in the pipeline API by [@Viicos](https://github.com/Viicos) in [#11626](https://github.com/pydantic/pydantic/pull/11626) * Fix deferred discriminator application logic by [@Viicos](https://github.com/Viicos) in [#11591](https://github.com/pydantic/pydantic/pull/11591) ### New Contributors[¶](#new-contributors "Permanent link") * [@cmenon12](https://github.com/cmenon12) made their first contribution in [#11562](https://github.com/pydantic/pydantic/pull/11562) * [@Jeukoh](https://github.com/Jeukoh) made their first contribution in [#11611](https://github.com/pydantic/pydantic/pull/11611) v2.11.0b2 (2025-03-17)[¶](#v2110b2-2025-03-17 "Permanent link") ---------------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b2) ### What's Changed[¶](#whats-changed_4 "Permanent link") #### Packaging[¶](#packaging_2 "Permanent link") * Bump `pydantic-core` to v2.32.0 by [@Viicos](https://github.com/Viicos) in [#11567](https://github.com/pydantic/pydantic/pull/11567) #### New Features[¶](#new-features_1 "Permanent link") * Add experimental support for free threading by [@Viicos](https://github.com/Viicos) in [#11516](https://github.com/pydantic/pydantic/pull/11516) #### Fixes[¶](#fixes_4 "Permanent link") * Fix `NotRequired` qualifier not taken into account in stringified annotation by [@Viicos](https://github.com/Viicos) in [#11559](https://github.com/pydantic/pydantic/pull/11559) ### New Contributors[¶](#new-contributors_1 "Permanent link") * [@joren485](https://github.com/joren485) made their first contribution in [#11547](https://github.com/pydantic/pydantic/pull/11547) v2.11.0b1 (2025-03-06)[¶](#v2110b1-2025-03-06 "Permanent link") ---------------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b1) ### What's Changed[¶](#whats-changed_5 "Permanent link") #### Packaging[¶](#packaging_3 "Permanent link") * Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11324 * Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11351 * Use the `typing-inspection` library by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11479 * Bump `pydantic-core` to `v2.31.1` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11526 #### New Features[¶](#new-features_2 "Permanent link") * Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in https://github.com/pydantic/pydantic/pull/10789 * Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11034 * Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11088 * Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11189 * Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11332 * Add support for validating v6, v7, v8 UUIDs by [@astei](https://github.com/astei) in https://github.com/pydantic/pydantic/pull/11436 * Improve alias configuration APIs by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11468 #### Changes[¶](#changes "Permanent link") * Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11032 * Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11168 * Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11169 * **Breaking Change:** Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10846 * Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11258 * Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10863 * Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11271 #### Performance[¶](#performance "Permanent link") * Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10769 * Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/10868 * Improve annotation application performance by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11186 * Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11255 * Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11244 * Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11384 * Bump `pydantic-core` and thus use `SchemaValidator` and `SchemaSerializer` caching by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11402 * Reuse cached core schemas for parametrized generic Pydantic models by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/11434 #### Fixes[¶](#fixes_5 "Permanent link") * Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10872 * Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10893 * Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11121 * Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11114 * Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11116 * Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11155 * Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11161 * Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11109 * Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11200 * Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in https://github.com/pydantic/pydantic/pull/11014 * Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10704 * Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11216 * Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11208 * Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11212 * Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11246 * Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11281 * Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11295 * Fix JSON Schema reference collection with `"examples"` keys by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11305 * Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11298 * Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11321 * Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in https://github.com/pydantic/pydantic/pull/11319 * Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11350 * Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11367 * Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11356 * Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in https://github.com/pydantic/pydantic/pull/11392 * Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11398 * Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11416 * Do not reuse validators and serializers during model rebuild by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11429 * Collect model fields when rebuilding a model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11388 * Allow cached properties to be altered on frozen models by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11432 * Fix tuple serialization for `Sequence` types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11435 * Fix: do not check for `__get_validators__` on classes where `__get_pydantic_core_schema__` is also defined by [@tlambert03](https://github.com/tlambert03) in https://github.com/pydantic/pydantic/pull/11444 * Allow callable instances to be used as serializers by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11451 * Improve error thrown when overriding field with a property by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11459 * Fix JSON Schema generation with referenceable core schemas holding JSON metadata by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11475 * Support strict specification on union member types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11481 * Implicitly set `validate_by_name` to `True` when `validate_by_alias` is `False` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11503 * Change type of `Any` when synthesizing `BaseSettings.__init__` signature in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11497 * Support type variable defaults referencing other type variables by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11520 * Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in https://github.com/pydantic/pydantic-core/pull/1583 * `dataclass` `InitVar` shouldn't be required on serialization by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic-core/pull/1602 New Contributors[¶](#new-contributors_2 "Permanent link") ---------------------------------------------------------- * [@FyZzyss](https://github.com/FyZzyss) made their first contribution in https://github.com/pydantic/pydantic/pull/10789 * [@tamird](https://github.com/tamird) made their first contribution in https://github.com/pydantic/pydantic/pull/10948 * [@felixxm](https://github.com/felixxm) made their first contribution in https://github.com/pydantic/pydantic/pull/11077 * [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in https://github.com/pydantic/pydantic/pull/11082 * [@Kharianne](https://github.com/Kharianne) made their first contribution in https://github.com/pydantic/pydantic/pull/11111 * [@mdaffad](https://github.com/mdaffad) made their first contribution in https://github.com/pydantic/pydantic/pull/11177 * [@thejcannon](https://github.com/thejcannon) made their first contribution in https://github.com/pydantic/pydantic/pull/11014 * [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in https://github.com/pydantic/pydantic/pull/11251 * [@usernameMAI](https://github.com/usernameMAI) made their first contribution in https://github.com/pydantic/pydantic/pull/11275 * [@ananiavito](https://github.com/ananiavito) made their first contribution in https://github.com/pydantic/pydantic/pull/11302 * [@pawamoy](https://github.com/pawamoy) made their first contribution in https://github.com/pydantic/pydantic/pull/11311 * [@Maze21127](https://github.com/Maze21127) made their first contribution in https://github.com/pydantic/pydantic/pull/11319 * [@kauabh](https://github.com/kauabh) made their first contribution in https://github.com/pydantic/pydantic/pull/11369 * [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in https://github.com/pydantic/pydantic/pull/11353 * [@tmpbeing](https://github.com/tmpbeing) made their first contribution in https://github.com/pydantic/pydantic/pull/11375 * [@petyosi](https://github.com/petyosi) made their first contribution in https://github.com/pydantic/pydantic/pull/11405 * [@austinyu](https://github.com/austinyu) made their first contribution in https://github.com/pydantic/pydantic/pull/11392 * [@mikeedjones](https://github.com/mikeedjones) made their first contribution in https://github.com/pydantic/pydantic/pull/11402 * [@astei](https://github.com/astei) made their first contribution in https://github.com/pydantic/pydantic/pull/11436 * [@dsayling](https://github.com/dsayling) made their first contribution in https://github.com/pydantic/pydantic/pull/11522 * [@sobolevn](https://github.com/sobolevn) made their first contribution in https://github.com/pydantic/pydantic-core/pull/1645 v2.11.0a2 (2025-02-10)[¶](#v2110a2-2025-02-10 "Permanent link") ---------------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a2) ### What's Changed[¶](#whats-changed_6 "Permanent link") Pydantic 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. #### Packaging[¶](#packaging_4 "Permanent link") * Bump `ruff` from 0.9.2 to 0.9.5 by [@Viicos](https://github.com/Viicos) in [#11407](https://github.com/pydantic/pydantic/pull/11407) * Bump `pydantic-core` to v2.29.0 by [@mikeedjones](https://github.com/mikeedjones) in [#11402](https://github.com/pydantic/pydantic/pull/11402) * Use locally-built rust with symbols & pgo by [@davidhewitt](https://github.com/davidhewitt) in [#11403](https://github.com/pydantic/pydantic/pull/11403) #### Performance[¶](#performance_1 "Permanent link") * Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in [#11384](https://github.com/pydantic/pydantic/pull/11384) #### Fixes[¶](#fixes_6 "Permanent link") * Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in [#11367](https://github.com/pydantic/pydantic/pull/11367) * Fix JSON Schema reference logic with `examples` keys by [@Viicos](https://github.com/Viicos) in [#11366](https://github.com/pydantic/pydantic/pull/11366) * Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in [#11356](https://github.com/pydantic/pydantic/pull/11356) * Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in [#11392](https://github.com/pydantic/pydantic/pull/11392) * Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in [#11398](https://github.com/pydantic/pydantic/pull/11398) * Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11416](https://github.com/pydantic/pydantic/pull/11416) ### New Contributors[¶](#new-contributors_3 "Permanent link") * [@kauabh](https://github.com/kauabh) made their first contribution in [#11369](https://github.com/pydantic/pydantic/pull/11369) * [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in [#11353](https://github.com/pydantic/pydantic/pull/11353) * [@tmpbeing](https://github.com/tmpbeing) made their first contribution in [#11375](https://github.com/pydantic/pydantic/pull/11375) * [@petyosi](https://github.com/petyosi) made their first contribution in [#11405](https://github.com/pydantic/pydantic/pull/11405) * [@austinyu](https://github.com/austinyu) made their first contribution in [#11392](https://github.com/pydantic/pydantic/pull/11392) * [@mikeedjones](https://github.com/mikeedjones) made their first contribution in [#11402](https://github.com/pydantic/pydantic/pull/11402) v2.11.0a1 (2025-01-30)[¶](#v2110a1-2025-01-30 "Permanent link") ---------------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a1) ### What's Changed[¶](#whats-changed_7 "Permanent link") Pydantic 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. #### Packaging[¶](#packaging_5 "Permanent link") * Bump dawidd6/action-download-artifact from 6 to 7 by [@dependabot](https://github.com/dependabot) in [#11018](https://github.com/pydantic/pydantic/pull/11018) * Re-enable memray related tests on Python 3.12+ by [@Viicos](https://github.com/Viicos) in [#11191](https://github.com/pydantic/pydantic/pull/11191) * Bump astral-sh/setup-uv to 5 by [@dependabot](https://github.com/dependabot) in [#11205](https://github.com/pydantic/pydantic/pull/11205) * Bump `ruff` to v0.9.0 by [@sydney-runkle](https://github.com/sydney-runkle) in [#11254](https://github.com/pydantic/pydantic/pull/11254) * Regular `uv.lock` deps update by [@sydney-runkle](https://github.com/sydney-runkle) in [#11333](https://github.com/pydantic/pydantic/pull/11333) * Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in [#11324](https://github.com/pydantic/pydantic/pull/11324) * Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in [#11351](https://github.com/pydantic/pydantic/pull/11351) * Bump `pydantic-core` to v2.28.0 by [@Viicos](https://github.com/Viicos) in [#11364](https://github.com/pydantic/pydantic/pull/11364) #### New Features[¶](#new-features_3 "Permanent link") * Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in [#10789](https://github.com/pydantic/pydantic/pull/10789) * Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034) * Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in [#11088](https://github.com/pydantic/pydantic/pull/11088) * Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in [#11189](https://github.com/pydantic/pydantic/pull/11189) * Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in [#11332](https://github.com/pydantic/pydantic/pull/11332) #### Changes[¶](#changes_1 "Permanent link") * Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in [#11032](https://github.com/pydantic/pydantic/pull/11032) * Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in [#11168](https://github.com/pydantic/pydantic/pull/11168) * Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in [#11169](https://github.com/pydantic/pydantic/pull/11169) * Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10846](https://github.com/pydantic/pydantic/pull/10846) * Move `deque` schema gen to `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#11239](https://github.com/pydantic/pydantic/pull/11239) * Move `Mapping` schema gen to `GenerateSchema` to complete removal of `prepare_annotations_for_known_type` workaround by [@sydney-runkle](https://github.com/sydney-runkle) in [#11247](https://github.com/pydantic/pydantic/pull/11247) * Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in [#11258](https://github.com/pydantic/pydantic/pull/11258) * Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#11271](https://github.com/pydantic/pydantic/pull/11271) #### Performance[¶](#performance_2 "Permanent link") * Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769) * Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in [#10863](https://github.com/pydantic/pydantic/pull/10863) * Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in [#10868](https://github.com/pydantic/pydantic/pull/10868) * Improve annotation application performance by [@Viicos](https://github.com/Viicos) in [#11186](https://github.com/pydantic/pydantic/pull/11186) * Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#11255](https://github.com/pydantic/pydantic/pull/11255) * Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) and [@MarkusSintonen](https://github.com/MarkusSintonen) in [#11244](https://github.com/pydantic/pydantic/pull/11244) #### Fixes[¶](#fixes_7 "Permanent link") * Add validation tests for `_internal/_validators.py` by [@tkasuz](https://github.com/tkasuz) in [#10763](https://github.com/pydantic/pydantic/pull/10763) * Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872) * Revert "ci: use locally built pydantic-core with debug symbols by [@sydney-runkle](https://github.com/sydney-runkle) in [#10942](https://github.com/pydantic/pydantic/pull/10942) * Re-enable all FastAPI tests by [@tamird](https://github.com/tamird) in [#10948](https://github.com/pydantic/pydantic/pull/10948) * Fix typo in HISTORY.md. by [@felixxm](https://github.com/felixxm) in [#11077](https://github.com/pydantic/pydantic/pull/11077) * Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11121](https://github.com/pydantic/pydantic/pull/11121) * Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in [#11114](https://github.com/pydantic/pydantic/pull/11114) * Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in [#11116](https://github.com/pydantic/pydantic/pull/11116) * Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in [#11155](https://github.com/pydantic/pydantic/pull/11155) * Add FastAPI and SQLModel to third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11044](https://github.com/pydantic/pydantic/pull/11044) * Fix conditional expressions syntax for third-party tests by [@Viicos](https://github.com/Viicos) in [#11162](https://github.com/pydantic/pydantic/pull/11162) * Move FastAPI tests to third-party workflow by [@Viicos](https://github.com/Viicos) in [#11164](https://github.com/pydantic/pydantic/pull/11164) * Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in [#11161](https://github.com/pydantic/pydantic/pull/11161) * Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in [#11109](https://github.com/pydantic/pydantic/pull/11109) * Include `openapi-python-client` check in issue creation for third-party failures, use `main` branch by [@sydney-runkle](https://github.com/sydney-runkle) in [#11182](https://github.com/pydantic/pydantic/pull/11182) * Add pandera third-party tests by [@Viicos](https://github.com/Viicos) in [#11193](https://github.com/pydantic/pydantic/pull/11193) * Add ODMantic third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11197](https://github.com/pydantic/pydantic/pull/11197) * Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in [#11200](https://github.com/pydantic/pydantic/pull/11200) * Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in [#11014](https://github.com/pydantic/pydantic/pull/11014) * Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in [#10704](https://github.com/pydantic/pydantic/pull/10704) * Re-enable Beanie third-party tests by [@Viicos](https://github.com/Viicos) in [#11214](https://github.com/pydantic/pydantic/pull/11214) * Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in [#11216](https://github.com/pydantic/pydantic/pull/11216) * Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in [#11208](https://github.com/pydantic/pydantic/pull/11208) * Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11212](https://github.com/pydantic/pydantic/pull/11212) * Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in [#11246](https://github.com/pydantic/pydantic/pull/11246) * Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11281](https://github.com/pydantic/pydantic/pull/11281) * Fix two misplaced sentences in validation errors documentation by [@ananiavito](https://github.com/ananiavito) in [#11302](https://github.com/pydantic/pydantic/pull/11302) * Fix mkdocstrings inventory example in documentation by [@pawamoy](https://github.com/pawamoy) in [#11311](https://github.com/pydantic/pydantic/pull/11311) * Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11295](https://github.com/pydantic/pydantic/pull/11295) * Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11298](https://github.com/pydantic/pydantic/pull/11298) * Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11321](https://github.com/pydantic/pydantic/pull/11321) * Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in [#11319](https://github.com/pydantic/pydantic/pull/11319) * Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in [#11350](https://github.com/pydantic/pydantic/pull/11350) * Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1583](https://github.com/pydantic/pydantic-core/pull/1583) ### New Contributors[¶](#new-contributors_4 "Permanent link") * [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789) * [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948) * [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077) * [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082) * [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111) * [@mdaffad](https://github.com/mdaffad) made their first contribution in [#11177](https://github.com/pydantic/pydantic/pull/11177) * [@thejcannon](https://github.com/thejcannon) made their first contribution in [#11014](https://github.com/pydantic/pydantic/pull/11014) * [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in [#11251](https://github.com/pydantic/pydantic/pull/11251) * [@usernameMAI](https://github.com/usernameMAI) made their first contribution in [#11275](https://github.com/pydantic/pydantic/pull/11275) * [@ananiavito](https://github.com/ananiavito) made their first contribution in [#11302](https://github.com/pydantic/pydantic/pull/11302) * [@pawamoy](https://github.com/pawamoy) made their first contribution in [#11311](https://github.com/pydantic/pydantic/pull/11311) * [@Maze21127](https://github.com/Maze21127) made their first contribution in [#11319](https://github.com/pydantic/pydantic/pull/11319) v2.10.6 (2025-01-23)[¶](#v2106-2025-01-23 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.6) ### What's Changed[¶](#whats-changed_8 "Permanent link") #### Fixes[¶](#fixes_8 "Permanent link") * Fix JSON Schema reference collection with `'examples'` keys by [@Viicos](https://github.com/Viicos) in [#11325](https://github.com/pydantic/pydantic/pull/11325) * Fix url python serialization by [@sydney-runkle](https://github.com/sydney-runkle) in [#11331](https://github.com/pydantic/pydantic/pull/11331) v2.10.5 (2025-01-08)[¶](#v2105-2025-01-08 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.5) ### What's Changed[¶](#whats-changed_9 "Permanent link") #### Fixes[¶](#fixes_9 "Permanent link") * Remove custom MRO implementation of Pydantic models by [@Viicos](https://github.com/Viicos) in [#11184](https://github.com/pydantic/pydantic/pull/11184) * Fix URL serialization for unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#11233](https://github.com/pydantic/pydantic/pull/11233) v2.10.4 (2024-12-18)[¶](#v2104-2024-12-18 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.4) ### What's Changed[¶](#whats-changed_10 "Permanent link") #### Packaging[¶](#packaging_6 "Permanent link") * Bump `pydantic-core` to v2.27.2 by [@davidhewitt](https://github.com/davidhewitt) in [#11138](https://github.com/pydantic/pydantic/pull/11138) #### Fixes[¶](#fixes_10 "Permanent link") * Fix for comparison of `AnyUrl` objects by [@alexprabhat99](https://github.com/alexprabhat99) in [#11082](https://github.com/pydantic/pydantic/pull/11082) * Properly fetch PEP 695 type params for functions, do not fetch annotations from signature by [@Viicos](https://github.com/Viicos) in [#11093](https://github.com/pydantic/pydantic/pull/11093) * Include JSON Schema input core schema in function schemas by [@Viicos](https://github.com/Viicos) in [#11085](https://github.com/pydantic/pydantic/pull/11085) * Add `len` to `_BaseUrl` to avoid TypeError by [@Kharianne](https://github.com/Kharianne) in [#11111](https://github.com/pydantic/pydantic/pull/11111) * Make sure the type reference is removed from the seen references by [@Viicos](https://github.com/Viicos) in [#11143](https://github.com/pydantic/pydantic/pull/11143) ### New Contributors[¶](#new-contributors_5 "Permanent link") * [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789) * [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948) * [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077) * [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082) * [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111) v2.10.3 (2024-12-03)[¶](#v2103-2024-12-03 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.3) ### What's Changed[¶](#whats-changed_11 "Permanent link") #### Fixes[¶](#fixes_11 "Permanent link") * Set fields when `defer_build` is set on Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10984](https://github.com/pydantic/pydantic/pull/10984) * Do not resolve the JSON Schema reference for `dict` core schema keys by [@Viicos](https://github.com/Viicos) in [#10989](https://github.com/pydantic/pydantic/pull/10989) * Use the globals of the function when evaluating the return type for `PlainSerializer` and `WrapSerializer` functions by [@Viicos](https://github.com/Viicos) in [#11008](https://github.com/pydantic/pydantic/pull/11008) * Fix host required enforcement for urls to be compatible with v2.9 behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11027](https://github.com/pydantic/pydantic/pull/11027) * Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034) * Fix url json schema in `serialization` mode by [@sydney-runkle](https://github.com/sydney-runkle) in [#11035](https://github.com/pydantic/pydantic/pull/11035) v2.10.2 (2024-11-25)[¶](#v2102-2024-11-25 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.2) ### What's Changed[¶](#whats-changed_12 "Permanent link") #### Fixes[¶](#fixes_12 "Permanent link") * Only evaluate FieldInfo annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769) * Do not evaluate annotations for private fields by [@Viicos](https://github.com/Viicos) in [#10962](https://github.com/pydantic/pydantic/pull/10962) * Support serialization as any for `Secret` types and `Url` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10947](https://github.com/pydantic/pydantic/pull/10947) * Fix type hint of `Field.default` to be compatible with Python 3.8 and 3.9 by [@Viicos](https://github.com/Viicos) in [#10972](https://github.com/pydantic/pydantic/pull/10972) * Add hashing support for URL types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10975](https://github.com/pydantic/pydantic/pull/10975) * Hide `BaseModel.__replace__` definition from type checkers by [@Viicos](https://github.com/Viicos) in [#10979](https://github.com/pydantic/pydantic/pull/10979) v2.10.1 (2024-11-21)[¶](#v2101-2024-11-21 "Permanent link") ------------------------------------------------------------ [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.1) ### What's Changed[¶](#whats-changed_13 "Permanent link") #### Packaging[¶](#packaging_7 "Permanent link") * Bump `pydantic-core` version to `v2.27.1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10938](https://github.com/pydantic/pydantic/pull/10938) #### Fixes[¶](#fixes_13 "Permanent link") * Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#10893](https://github.com/pydantic/pydantic/pull/10893) * Relax check for validated data in `default_factory` utils by [@sydney-runkle](https://github.com/sydney-runkle) in [#10909](https://github.com/pydantic/pydantic/pull/10909) * Fix type checking issue with `model_fields` and `model_computed_fields` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10911](https://github.com/pydantic/pydantic/pull/10911) * Use the parent configuration during schema generation for stdlib `dataclass`es by [@sydney-runkle](https://github.com/sydney-runkle) in [#10928](https://github.com/pydantic/pydantic/pull/10928) * Use the `globals` of the function when evaluating the return type of serializers and `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10929](https://github.com/pydantic/pydantic/pull/10929) * Fix URL constraint application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10922](https://github.com/pydantic/pydantic/pull/10922) * Fix URL equality with different validation methods by [@sydney-runkle](https://github.com/sydney-runkle) in [#10934](https://github.com/pydantic/pydantic/pull/10934) * Fix JSON schema title when specified as `''` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10936](https://github.com/pydantic/pydantic/pull/10936) * Fix `python` mode serialization for `complex` inference by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic-core#1549](https://github.com/pydantic/pydantic-core/pull/1549) ### New Contributors[¶](#new-contributors_6 "Permanent link") v2.10.0 (2024-11-20)[¶](#v2100-2024-11-20 "Permanent link") ------------------------------------------------------------ The code released in v2.10.0 is practically identical to that of v2.10.0b2. [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0) See the [v2.10 release blog post](https://pydantic.dev/articles/pydantic-v2-10-release) for the highlights! ### What's Changed[¶](#whats-changed_14 "Permanent link") #### Packaging[¶](#packaging_8 "Permanent link") * Bump `pydantic-core` to `v2.27.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825) * Replaced pdm with uv by [@frfahim](https://github.com/frfahim) in [#10727](https://github.com/pydantic/pydantic/pull/10727) #### New Features[¶](#new-features_4 "Permanent link") * Support `fractions.Fraction` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10318](https://github.com/pydantic/pydantic/pull/10318) * Support `Hashable` for json validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10324](https://github.com/pydantic/pydantic/pull/10324) * Add a `SocketPath` type for `linux` systems by [@theunkn0wn1](https://github.com/theunkn0wn1) in [#10378](https://github.com/pydantic/pydantic/pull/10378) * Allow arbitrary refs in JSON schema `examples` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10417](https://github.com/pydantic/pydantic/pull/10417) * Support `defer_build` for Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10313](https://github.com/pydantic/pydantic/pull/10313) * Adding v1 / v2 incompatibility warning for nested v1 model by [@sydney-runkle](https://github.com/sydney-runkle) in [#10431](https://github.com/pydantic/pydantic/pull/10431) * Add support for unpacked `TypedDict` to type hint variadic keyword arguments with `@validate_call` by [@Viicos](https://github.com/Viicos) in [#10416](https://github.com/pydantic/pydantic/pull/10416) * Support compiled patterns in `protected_namespaces` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10522](https://github.com/pydantic/pydantic/pull/10522) * Add support for `propertyNames` in JSON schema by [@FlorianSW](https://github.com/FlorianSW) in [#10478](https://github.com/pydantic/pydantic/pull/10478) * Adding `__replace__` protocol for Python 3.13+ support by [@sydney-runkle](https://github.com/sydney-runkle) in [#10596](https://github.com/pydantic/pydantic/pull/10596) * Expose public `sort` method for JSON schema generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10595](https://github.com/pydantic/pydantic/pull/10595) * Add runtime validation of `@validate_call` callable argument by [@kc0506](https://github.com/kc0506) in [#10627](https://github.com/pydantic/pydantic/pull/10627) * Add `experimental_allow_partial` support by [@samuelcolvin](https://github.com/samuelcolvin) in [#10748](https://github.com/pydantic/pydantic/pull/10748) * Support default factories taking validated data as an argument by [@Viicos](https://github.com/Viicos) in [#10678](https://github.com/pydantic/pydantic/pull/10678) * Allow subclassing `ValidationError` and `PydanticCustomError` by [@Youssefares](https://github.com/Youssefares) in [pydantic/pydantic-core#1413](https://github.com/pydantic/pydantic-core/pull/1413) * Add `trailing-strings` support to `experimental_allow_partial` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825) * Add `rebuild()` method for `TypeAdapter` and simplify `defer_build` patterns by [@sydney-runkle](https://github.com/sydney-runkle) in [#10537](https://github.com/pydantic/pydantic/pull/10537) * Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872) #### Changes[¶](#changes_2 "Permanent link") * Don't allow customization of `SchemaGenerator` until interface is more stable by [@sydney-runkle](https://github.com/sydney-runkle) in [#10303](https://github.com/pydantic/pydantic/pull/10303) * Cleanly `defer_build` on `TypeAdapters`, removing experimental flag by [@sydney-runkle](https://github.com/sydney-runkle) in [#10329](https://github.com/pydantic/pydantic/pull/10329) * Fix `mro` of generic subclass by [@kc0506](https://github.com/kc0506) in [#10100](https://github.com/pydantic/pydantic/pull/10100) * Strip whitespaces on JSON Schema title generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10404](https://github.com/pydantic/pydantic/pull/10404) * Use `b64decode` and `b64encode` for `Base64Bytes` type by [@sydney-runkle](https://github.com/sydney-runkle) in [#10486](https://github.com/pydantic/pydantic/pull/10486) * Relax protected namespace config default by [@sydney-runkle](https://github.com/sydney-runkle) in [#10441](https://github.com/pydantic/pydantic/pull/10441) * Revalidate parametrized generics if instance's origin is subclass of OG class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10666](https://github.com/pydantic/pydantic/pull/10666) * Warn if configuration is specified on the `@dataclass` decorator and with the `__pydantic_config__` attribute by [@sydney-runkle](https://github.com/sydney-runkle) in [#10406](https://github.com/pydantic/pydantic/pull/10406) * Recommend against using `Ellipsis` (...) with `Field` by [@Viicos](https://github.com/Viicos) in [#10661](https://github.com/pydantic/pydantic/pull/10661) * Migrate to subclassing instead of annotated approach for pydantic url types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10662](https://github.com/pydantic/pydantic/pull/10662) * Change JSON schema generation of `Literal`s and `Enums` by [@Viicos](https://github.com/Viicos) in [#10692](https://github.com/pydantic/pydantic/pull/10692) * Simplify unions involving `Any` or `Never` when replacing type variables by [@Viicos](https://github.com/Viicos) in [#10338](https://github.com/pydantic/pydantic/pull/10338) * Do not require padding when decoding `base64` bytes by [@bschoenmaeckers](https://github.com/bschoenmaeckers) in [pydantic/pydantic-core#1448](https://github.com/pydantic/pydantic-core/pull/1448) * Support dates all the way to 1BC by [@changhc](https://github.com/changhc) in [pydantic/speedate#77](https://github.com/pydantic/speedate/pull/77) #### Performance[¶](#performance_3 "Permanent link") * Schema cleaning: skip unnecessary copies during schema walking by [@Viicos](https://github.com/Viicos) in [#10286](https://github.com/pydantic/pydantic/pull/10286) * Refactor namespace logic for annotations evaluation by [@Viicos](https://github.com/Viicos) in [#10530](https://github.com/pydantic/pydantic/pull/10530) * Improve email regexp on edge cases by [@AlekseyLobanov](https://github.com/AlekseyLobanov) in [#10601](https://github.com/pydantic/pydantic/pull/10601) * `CoreMetadata` refactor with an emphasis on documentation, schema build time performance, and reducing complexity by [@sydney-runkle](https://github.com/sydney-runkle) in [#10675](https://github.com/pydantic/pydantic/pull/10675) #### Fixes[¶](#fixes_14 "Permanent link") * Remove guarding check on `computed_field` with `field_serializer` by [@nix010](https://github.com/nix010) in [#10390](https://github.com/pydantic/pydantic/pull/10390) * Fix `Predicate` issue in `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10321](https://github.com/pydantic/pydantic/pull/10321) * Fixing `annotated-types` bound by [@sydney-runkle](https://github.com/sydney-runkle) in [#10327](https://github.com/pydantic/pydantic/pull/10327) * Turn `tzdata` install requirement into optional `timezone` dependency by [@jakob-keller](https://github.com/jakob-keller) in [#10331](https://github.com/pydantic/pydantic/pull/10331) * Use correct types namespace when building `namedtuple` core schemas by [@Viicos](https://github.com/Viicos) in [#10337](https://github.com/pydantic/pydantic/pull/10337) * Fix evaluation of stringified annotations during namespace inspection by [@Viicos](https://github.com/Viicos) in [#10347](https://github.com/pydantic/pydantic/pull/10347) * Fix `IncEx` type alias definition by [@Viicos](https://github.com/Viicos) in [#10339](https://github.com/pydantic/pydantic/pull/10339) * Do not error when trying to evaluate annotations of private attributes by [@Viicos](https://github.com/Viicos) in [#10358](https://github.com/pydantic/pydantic/pull/10358) * Fix nested type statement by [@kc0506](https://github.com/kc0506) in [#10369](https://github.com/pydantic/pydantic/pull/10369) * Improve typing of `ModelMetaclass.mro` by [@Viicos](https://github.com/Viicos) in [#10372](https://github.com/pydantic/pydantic/pull/10372) * Fix class access of deprecated `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10391](https://github.com/pydantic/pydantic/pull/10391) * Make sure `inspect.iscoroutinefunction` works on coroutines decorated with `@validate_call` by [@MovisLi](https://github.com/MovisLi) in [#10374](https://github.com/pydantic/pydantic/pull/10374) * Fix `NameError` when using `validate_call` with PEP 695 on a class by [@kc0506](https://github.com/kc0506) in [#10380](https://github.com/pydantic/pydantic/pull/10380) * Fix `ZoneInfo` with various invalid types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10408](https://github.com/pydantic/pydantic/pull/10408) * Fix `PydanticUserError` on empty `model_config` with annotations by [@cdwilson](https://github.com/cdwilson) in [#10412](https://github.com/pydantic/pydantic/pull/10412) * Fix variance issue in `_IncEx` type alias, only allow `True` by [@Viicos](https://github.com/Viicos) in [#10414](https://github.com/pydantic/pydantic/pull/10414) * Fix serialization schema generation when using `PlainValidator` by [@Viicos](https://github.com/Viicos) in [#10427](https://github.com/pydantic/pydantic/pull/10427) * Fix schema generation error when serialization schema holds references by [@Viicos](https://github.com/Viicos) in [#10444](https://github.com/pydantic/pydantic/pull/10444) * Inline references if possible when generating schema for `json_schema_input_type` by [@Viicos](https://github.com/Viicos) in [#10439](https://github.com/pydantic/pydantic/pull/10439) * Fix recursive arguments in `Representation` by [@Viicos](https://github.com/Viicos) in [#10480](https://github.com/pydantic/pydantic/pull/10480) * Fix representation for builtin function types by [@kschwab](https://github.com/kschwab) in [#10479](https://github.com/pydantic/pydantic/pull/10479) * Add python validators for decimal constraints (`max_digits` and `decimal_places`) by [@sydney-runkle](https://github.com/sydney-runkle) in [#10506](https://github.com/pydantic/pydantic/pull/10506) * Only fetch `__pydantic_core_schema__` from the current class during schema generation by [@Viicos](https://github.com/Viicos) in [#10518](https://github.com/pydantic/pydantic/pull/10518) * Fix `stacklevel` on deprecation warnings for `BaseModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10520](https://github.com/pydantic/pydantic/pull/10520) * Fix warning `stacklevel` in `BaseModel.__init__` by [@Viicos](https://github.com/Viicos) in [#10526](https://github.com/pydantic/pydantic/pull/10526) * Improve error handling for in-evaluable refs for discriminator application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10440](https://github.com/pydantic/pydantic/pull/10440) * Change the signature of `ConfigWrapper.core_config` to take the title directly by [@Viicos](https://github.com/Viicos) in [#10562](https://github.com/pydantic/pydantic/pull/10562) * Do not use the previous config from the stack for dataclasses without config by [@Viicos](https://github.com/Viicos) in [#10576](https://github.com/pydantic/pydantic/pull/10576) * Fix serialization for IP types with `mode='python'` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10594](https://github.com/pydantic/pydantic/pull/10594) * Support constraint application for `Base64Etc` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10584](https://github.com/pydantic/pydantic/pull/10584) * Fix `validate_call` ignoring `Field` in `Annotated` by [@kc0506](https://github.com/kc0506) in [#10610](https://github.com/pydantic/pydantic/pull/10610) * Raise an error when `Self` is invalid by [@kc0506](https://github.com/kc0506) in [#10609](https://github.com/pydantic/pydantic/pull/10609) * Using `core_schema.InvalidSchema` instead of metadata injection + checks by [@sydney-runkle](https://github.com/sydney-runkle) in [#10523](https://github.com/pydantic/pydantic/pull/10523) * Tweak type alias logic by [@kc0506](https://github.com/kc0506) in [#10643](https://github.com/pydantic/pydantic/pull/10643) * Support usage of `type` with `typing.Self` and type aliases by [@kc0506](https://github.com/kc0506) in [#10621](https://github.com/pydantic/pydantic/pull/10621) * Use overloads for `Field` and `PrivateAttr` functions by [@Viicos](https://github.com/Viicos) in [#10651](https://github.com/pydantic/pydantic/pull/10651) * Clean up the `mypy` plugin implementation by [@Viicos](https://github.com/Viicos) in [#10669](https://github.com/pydantic/pydantic/pull/10669) * Properly check for `typing_extensions` variant of `TypeAliasType` by [@Daraan](https://github.com/Daraan) in [#10713](https://github.com/pydantic/pydantic/pull/10713) * Allow any mapping in `BaseModel.model_copy()` by [@Viicos](https://github.com/Viicos) in [#10751](https://github.com/pydantic/pydantic/pull/10751) * Fix `isinstance` behavior for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10766](https://github.com/pydantic/pydantic/pull/10766) * Ensure `cached_property` can be set on Pydantic models by [@Viicos](https://github.com/Viicos) in [#10774](https://github.com/pydantic/pydantic/pull/10774) * Fix equality checks for primitives in literals by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1459](https://github.com/pydantic/pydantic-core/pull/1459) * Properly enforce `host_required` for URLs by [@Viicos](https://github.com/Viicos) in [pydantic/pydantic-core#1488](https://github.com/pydantic/pydantic-core/pull/1488) * Fix when `coerce_numbers_to_str` enabled and string has invalid Unicode character by [@andrey-berenda](https://github.com/andrey-berenda) in [pydantic/pydantic-core#1515](https://github.com/pydantic/pydantic-core/pull/1515) * Fix serializing `complex` values in `Enum`s by [@changhc](https://github.com/changhc) in [pydantic/pydantic-core#1524](https://github.com/pydantic/pydantic-core/pull/1524) * Refactor `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#10725](https://github.com/pydantic/pydantic/pull/10725) * Support intuitive equality for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10798](https://github.com/pydantic/pydantic/pull/10798) * Add `bytearray` to `TypeAdapter.validate_json` signature by [@samuelcolvin](https://github.com/samuelcolvin) in [#10802](https://github.com/pydantic/pydantic/pull/10802) * Ensure class access of method descriptors is performed when used as a default with `Field` by [@Viicos](https://github.com/Viicos) in [#10816](https://github.com/pydantic/pydantic/pull/10816) * Fix circular import with `validate_call` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10807](https://github.com/pydantic/pydantic/pull/10807) * Fix error when using type aliases referencing other type aliases by [@Viicos](https://github.com/Viicos) in [#10809](https://github.com/pydantic/pydantic/pull/10809) * Fix `IncEx` type alias to be compatible with mypy by [@Viicos](https://github.com/Viicos) in [#10813](https://github.com/pydantic/pydantic/pull/10813) * Make `__signature__` a lazy property, do not deepcopy defaults by [@Viicos](https://github.com/Viicos) in [#10818](https://github.com/pydantic/pydantic/pull/10818) * Make `__signature__` lazy for dataclasses, too by [@sydney-runkle](https://github.com/sydney-runkle) in [#10832](https://github.com/pydantic/pydantic/pull/10832) * Subclass all single host url classes from `AnyUrl` to preserve behavior from v2.9 by [@sydney-runkle](https://github.com/sydney-runkle) in [#10856](https://github.com/pydantic/pydantic/pull/10856) ### New Contributors[¶](#new-contributors_7 "Permanent link") * [@jakob-keller](https://github.com/jakob-keller) made their first contribution in [#10331](https://github.com/pydantic/pydantic/pull/10331) * [@MovisLi](https://github.com/MovisLi) made their first contribution in [#10374](https://github.com/pydantic/pydantic/pull/10374) * [@joaopalmeiro](https://github.com/joaopalmeiro) made their first contribution in [#10405](https://github.com/pydantic/pydantic/pull/10405) * [@theunkn0wn1](https://github.com/theunkn0wn1) made their first contribution in [#10378](https://github.com/pydantic/pydantic/pull/10378) * [@cdwilson](https://github.com/cdwilson) made their first contribution in [#10412](https://github.com/pydantic/pydantic/pull/10412) * [@dlax](https://github.com/dlax) made their first contribution in [#10421](https://github.com/pydantic/pydantic/pull/10421) * [@kschwab](https://github.com/kschwab) made their first contribution in [#10479](https://github.com/pydantic/pydantic/pull/10479) * [@santibreo](https://github.com/santibreo) made their first contribution in [#10453](https://github.com/pydantic/pydantic/pull/10453) * [@FlorianSW](https://github.com/FlorianSW) made their first contribution in [#10478](https://github.com/pydantic/pydantic/pull/10478) * [@tkasuz](https://github.com/tkasuz) made their first contribution in [#10555](https://github.com/pydantic/pydantic/pull/10555) * [@AlekseyLobanov](https://github.com/AlekseyLobanov) made their first contribution in [#10601](https://github.com/pydantic/pydantic/pull/10601) * [@NiclasvanEyk](https://github.com/NiclasvanEyk) made their first contribution in [#10667](https://github.com/pydantic/pydantic/pull/10667) * [@mschoettle](https://github.com/mschoettle) made their first contribution in [#10677](https://github.com/pydantic/pydantic/pull/10677) * [@Daraan](https://github.com/Daraan) made their first contribution in [#10713](https://github.com/pydantic/pydantic/pull/10713) * [@k4nar](https://github.com/k4nar) made their first contribution in [#10736](https://github.com/pydantic/pydantic/pull/10736) * [@UriyaHarpeness](https://github.com/UriyaHarpeness) made their first contribution in [#10740](https://github.com/pydantic/pydantic/pull/10740) * [@frfahim](https://github.com/frfahim) made their first contribution in [#10727](https://github.com/pydantic/pydantic/pull/10727) v2.10.0b2 (2024-11-13)[¶](#v2100b2-2024-11-13 "Permanent link") ---------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b2) for details. v2.10.0b1 (2024-11-06)[¶](#v2100b1-2024-11-06 "Permanent link") ---------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b1) for details. v2.9.2 (2024-09-17)[¶](#v292-2024-09-17 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.9.2) ### What's Changed[¶](#whats-changed_15 "Permanent link") #### Fixes[¶](#fixes_15 "Permanent link") * Do not error when trying to evaluate annotations of private attributes by [@Viicos](https://github.com/Viicos) in [#10358](https://github.com/pydantic/pydantic/pull/10358) * Adding notes on designing sound `Callable` discriminators by [@sydney-runkle](https://github.com/sydney-runkle) in [#10400](https://github.com/pydantic/pydantic/pull/10400) * Fix serialization schema generation when using `PlainValidator` by [@Viicos](https://github.com/Viicos) in [#10427](https://github.com/pydantic/pydantic/pull/10427) * Fix `Union` serialization warnings by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1449](https://github.com/pydantic/pydantic-core/pull/1449) * Fix variance issue in `_IncEx` type alias, only allow `True` by [@Viicos](https://github.com/Viicos) in [#10414](https://github.com/pydantic/pydantic/pull/10414) * Fix `ZoneInfo` validation with various invalid types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10408](https://github.com/pydantic/pydantic/pull/10408) v2.9.1 (2024-09-09)[¶](#v291-2024-09-09 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.9.1) ### What's Changed[¶](#whats-changed_16 "Permanent link") #### Fixes[¶](#fixes_16 "Permanent link") * Fix Predicate issue in v2.9.0 by [@sydney-runkle](https://github.com/sydney-runkle) in [#10321](https://github.com/pydantic/pydantic/pull/10321) * Fixing `annotated-types` bound to `>=0.6.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10327](https://github.com/pydantic/pydantic/pull/10327) * Turn `tzdata` install requirement into optional `timezone` dependency by [@jakob-keller](https://github.com/jakob-keller) in [#10331](https://github.com/pydantic/pydantic/pull/10331) * Fix `IncExc` type alias definition by [@Viicos](https://github.com/Viicos) in [#10339](https://github.com/pydantic/pydantic/pull/10339) * Use correct types namespace when building namedtuple core schemas by [@Viicos](https://github.com/Viicos) in [#10337](https://github.com/pydantic/pydantic/pull/10337) * Fix evaluation of stringified annotations during namespace inspection by [@Viicos](https://github.com/Viicos) in [#10347](https://github.com/pydantic/pydantic/pull/10347) * Fix tagged union serialization with alias generators by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1442](https://github.com/pydantic/pydantic-core/pull/1442) v2.9.0 (2024-09-05)[¶](#v290-2024-09-05 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.9.0) The code released in v2.9.0 is practically identical to that of v2.9.0b2. ### What's Changed[¶](#whats-changed_17 "Permanent link") #### Packaging[¶](#packaging_9 "Permanent link") * Bump `ruff` to `v0.5.0` and `pyright` to `v1.1.369` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9801](https://github.com/pydantic/pydantic/pull/9801) * Bump `pydantic-extra-types` to `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9832](https://github.com/pydantic/pydantic/pull/9832) * Support compatibility with `pdm v2.18.1` by [@Viicos](https://github.com/Viicos) in [#10138](https://github.com/pydantic/pydantic/pull/10138) * Bump `v1` version stub to `v1.10.18` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10214](https://github.com/pydantic/pydantic/pull/10214) * Bump `pydantic-core` to `v2.23.2` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10311](https://github.com/pydantic/pydantic/pull/10311) #### New Features[¶](#new-features_5 "Permanent link") * Add support for `ZoneInfo` by [@Youssefares](https://github.com/Youssefares) in [#9896](https://github.com/pydantic/pydantic/pull/9896) * Add `Config.val_json_bytes` by [@josh-newman](https://github.com/josh-newman) in [#9770](https://github.com/pydantic/pydantic/pull/9770) * Add DSN for Snowflake by [@aditkumar72](https://github.com/aditkumar72) in [#10128](https://github.com/pydantic/pydantic/pull/10128) * Support `complex` number by [@changhc](https://github.com/changhc) in [#9654](https://github.com/pydantic/pydantic/pull/9654) * Add support for `annotated_types.Not` by [@aditkumar72](https://github.com/aditkumar72) in [#10210](https://github.com/pydantic/pydantic/pull/10210) * Allow `WithJsonSchema` to inject `$ref`s w/ `http` or `https` links by [@dAIsySHEng1](https://github.com/dAIsySHEng1) in [#9863](https://github.com/pydantic/pydantic/pull/9863) * Allow validators to customize validation JSON schema by [@Viicos](https://github.com/Viicos) in [#10094](https://github.com/pydantic/pydantic/pull/10094) * Support parametrized `PathLike` types by [@nix010](https://github.com/nix010) in [#9764](https://github.com/pydantic/pydantic/pull/9764) * Add tagged union serializer that attempts to use `str` or `callable` discriminators to select the correct serializer by [@sydney-runkle](https://github.com/sydney-runkle) in in [pydantic/pydantic-core#1397](https://github.com/pydantic/pydantic-core/pull/1397) #### Changes[¶](#changes_3 "Permanent link") * Breaking Change: Merge `dict` type `json_schema_extra` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9792](https://github.com/pydantic/pydantic/pull/9792) * For more info (how to replicate old behavior) on this change, see [here](https://docs.pydantic.dev/dev/concepts/json_schema/#merging-json_schema_extra) * Refactor annotation injection for known (often generic) types by [@sydney-runkle](https://github.com/sydney-runkle) in [#9979](https://github.com/pydantic/pydantic/pull/9979) * Move annotation compatibility errors to validation phase by [@sydney-runkle](https://github.com/sydney-runkle) in [#9999](https://github.com/pydantic/pydantic/pull/9999) * Improve runtime errors for string constraints like `pattern` for incompatible types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10158](https://github.com/pydantic/pydantic/pull/10158) * Remove `'allOf'` JSON schema workarounds by [@dpeachey](https://github.com/dpeachey) in [#10029](https://github.com/pydantic/pydantic/pull/10029) * Remove `typed_dict_cls` data from `CoreMetadata` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10180](https://github.com/pydantic/pydantic/pull/10180) * Deprecate passing a dict to the `Examples` class by [@Viicos](https://github.com/Viicos) in [#10181](https://github.com/pydantic/pydantic/pull/10181) * Remove `initial_metadata` from internal metadata construct by [@sydney-runkle](https://github.com/sydney-runkle) in [#10194](https://github.com/pydantic/pydantic/pull/10194) * Use `re.Pattern.search` instead of `re.Pattern.match` for consistency with `rust` behavior by [@tinez](https://github.com/tinez) in [pydantic/pydantic-core#1368](https://github.com/pydantic/pydantic-core/pull/1368) * Show value of wrongly typed data in `pydantic-core` serialization warning by [@BoxyUwU](https://github.com/BoxyUwU) in [pydantic/pydantic-core#1377](https://github.com/pydantic/pydantic-core/pull/1377) * Breaking Change: in `pydantic-core`, change `metadata` type hint in core schemas from `Any` -> `Dict[str, Any] | None` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1411](https://github.com/pydantic/pydantic-core/pull/1411) * Raise helpful warning when `self` isn't returned from model validator by [@sydney-runkle](https://github.com/sydney-runkle) in [#10255](https://github.com/pydantic/pydantic/pull/10255) #### Performance[¶](#performance_4 "Permanent link") * Initial start at improving import times for modules, using caching primarily by [@sydney-runkle](https://github.com/sydney-runkle) in [#10009](https://github.com/pydantic/pydantic/pull/10009) * Using cached internal import for `BaseModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10013](https://github.com/pydantic/pydantic/pull/10013) * Simplify internal generics logic - remove generator overhead by [@sydney-runkle](https://github.com/sydney-runkle) in [#10059](https://github.com/pydantic/pydantic/pull/10059) * Remove default module globals from types namespace by [@sydney-runkle](https://github.com/sydney-runkle) in [#10123](https://github.com/pydantic/pydantic/pull/10123) * Performance boost: skip caching parent namespaces in most cases by [@sydney-runkle](https://github.com/sydney-runkle) in [#10113](https://github.com/pydantic/pydantic/pull/10113) * Update ns stack with already copied ns by [@sydney-runkle](https://github.com/sydney-runkle) in [#10267](https://github.com/pydantic/pydantic/pull/10267) ##### Minor Internal Improvements[¶](#minor-internal-improvements "Permanent link") * ⚡️ Speed up `multiple_of_validator()` by 31% in `pydantic/_internal/_validators.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9839](https://github.com/pydantic/pydantic/pull/9839) * ⚡️ Speed up `ModelPrivateAttr.__set_name__()` by 18% in `pydantic/fields.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9841](https://github.com/pydantic/pydantic/pull/9841) * ⚡️ Speed up `dataclass()` by 7% in `pydantic/dataclasses.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9843](https://github.com/pydantic/pydantic/pull/9843) * ⚡️ Speed up function `_field_name_for_signature` by 37% in `pydantic/_internal/_signature.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9951](https://github.com/pydantic/pydantic/pull/9951) * ⚡️ Speed up method `GenerateSchema._unpack_refs_defs` by 26% in `pydantic/_internal/_generate_schema.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9949](https://github.com/pydantic/pydantic/pull/9949) * ⚡️ Speed up function `apply_each_item_validators` by 100% in `pydantic/_internal/_generate_schema.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9950](https://github.com/pydantic/pydantic/pull/9950) * ⚡️ Speed up method `ConfigWrapper.core_config` by 28% in `pydantic/_internal/_config.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9953](https://github.com/pydantic/pydantic/pull/9953) #### Fixes[¶](#fixes_17 "Permanent link") * Respect `use_enum_values` on `Literal` types by [@kwint](https://github.com/kwint) in [#9787](https://github.com/pydantic/pydantic/pull/9787) * Prevent type error for exotic `BaseModel/RootModel` inheritance by [@dmontagu](https://github.com/dmontagu) in [#9913](https://github.com/pydantic/pydantic/pull/9913) * Fix typing issue with field\_validator-decorated methods by [@dmontagu](https://github.com/dmontagu) in [#9914](https://github.com/pydantic/pydantic/pull/9914) * Replace `str` type annotation with `Any` in validator factories in documentation on validators by [@maximilianfellhuber](https://github.com/maximilianfellhuber) in [#9885](https://github.com/pydantic/pydantic/pull/9885) * Fix `ComputedFieldInfo.wrapped_property` pointer when a property setter is assigned by [@tlambert03](https://github.com/tlambert03) in [#9892](https://github.com/pydantic/pydantic/pull/9892) * Fix recursive typing of `main.IncEnx` by [@tlambert03](https://github.com/tlambert03) in [#9924](https://github.com/pydantic/pydantic/pull/9924) * Allow usage of `type[Annotated[...]]` by [@Viicos](https://github.com/Viicos) in [#9932](https://github.com/pydantic/pydantic/pull/9932) * `mypy` plugin: handle frozen fields on a per-field basis by [@dmontagu](https://github.com/dmontagu) in [#9935](https://github.com/pydantic/pydantic/pull/9935) * Fix typo in `invalid-annotated-type` error code by [@sydney-runkle](https://github.com/sydney-runkle) in [#9948](https://github.com/pydantic/pydantic/pull/9948) * Simplify schema generation for `uuid`, `url`, and `ip` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#9975](https://github.com/pydantic/pydantic/pull/9975) * Move `date` schemas to `_generate_schema.py` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9976](https://github.com/pydantic/pydantic/pull/9976) * Move `decimal.Decimal` validation to `_generate_schema.py` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9977](https://github.com/pydantic/pydantic/pull/9977) * Simplify IP address schema in `_std_types_schema.py` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9959](https://github.com/pydantic/pydantic/pull/9959) * Fix type annotations for some potentially generic `GenerateSchema.match_type` options by [@sydney-runkle](https://github.com/sydney-runkle) in [#9961](https://github.com/pydantic/pydantic/pull/9961) * Add class name to "has conflict" warnings by [@msabramo](https://github.com/msabramo) in [#9964](https://github.com/pydantic/pydantic/pull/9964) * Fix `dataclass` ignoring `default_factory` passed in Annotated by [@kc0506](https://github.com/kc0506) in [#9971](https://github.com/pydantic/pydantic/pull/9971) * Fix `Sequence` ignoring `discriminator` by [@kc0506](https://github.com/kc0506) in [#9980](https://github.com/pydantic/pydantic/pull/9980) * Fix typing for `IPvAnyAddress` and `IPvAnyInterface` by [@haoyun](https://github.com/haoyun) in [#9990](https://github.com/pydantic/pydantic/pull/9990) * Fix false positives on v1 models in `mypy` plugin for `from_orm` check requiring from\_attributes=True config by [@radekwlsk](https://github.com/radekwlsk) in [#9938](https://github.com/pydantic/pydantic/pull/9938) * Apply `strict=True` to `__init__` in `mypy` plugin by [@kc0506](https://github.com/kc0506) in [#9998](https://github.com/pydantic/pydantic/pull/9998) * Refactor application of `deque` annotations by [@sydney-runkle](https://github.com/sydney-runkle) in [#10018](https://github.com/pydantic/pydantic/pull/10018) * Raise a better user error when failing to evaluate a forward reference by [@Viicos](https://github.com/Viicos) in [#10030](https://github.com/pydantic/pydantic/pull/10030) * Fix evaluation of `__pydantic_extra__` annotation in specific circumstances by [@Viicos](https://github.com/Viicos) in [#10070](https://github.com/pydantic/pydantic/pull/10070) * Fix `frozen` enforcement for `dataclasses` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10066](https://github.com/pydantic/pydantic/pull/10066) * Remove logic to handle unused `__get_pydantic_core_schema__` signature by [@Viicos](https://github.com/Viicos) in [#10075](https://github.com/pydantic/pydantic/pull/10075) * Use `is_annotated` consistently by [@Viicos](https://github.com/Viicos) in [#10095](https://github.com/pydantic/pydantic/pull/10095) * Fix `PydanticDeprecatedSince26` typo by [@kc0506](https://github.com/kc0506) in [#10101](https://github.com/pydantic/pydantic/pull/10101) * Improve `pyright` tests, refactor model decorators signatures by [@Viicos](https://github.com/Viicos) in [#10092](https://github.com/pydantic/pydantic/pull/10092) * Fix `ip` serialization logic by [@sydney-runkle](https://github.com/sydney-runkle) in [#10112](https://github.com/pydantic/pydantic/pull/10112) * Warn when frozen defined twice for `dataclasses` by [@mochi22](https://github.com/mochi22) in [#10082](https://github.com/pydantic/pydantic/pull/10082) * Do not compute JSON Schema default when plain serializers are used with `when_used` set to `'json-unless-none'` and the default value is `None` by [@Viicos](https://github.com/Viicos) in [#10121](https://github.com/pydantic/pydantic/pull/10121) * Fix `ImportString` special cases by [@sydney-runkle](https://github.com/sydney-runkle) in [#10137](https://github.com/pydantic/pydantic/pull/10137) * Blacklist default globals to support exotic user code with `__` prefixed annotations by [@sydney-runkle](https://github.com/sydney-runkle) in [#10136](https://github.com/pydantic/pydantic/pull/10136) * Handle `nullable` schemas with `serialization` schema available during JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#10132](https://github.com/pydantic/pydantic/pull/10132) * Reorganize `BaseModel` annotations by [@kc0506](https://github.com/kc0506) in [#10110](https://github.com/pydantic/pydantic/pull/10110) * Fix core schema simplification when serialization schemas are involved in specific scenarios by [@Viicos](https://github.com/Viicos) in [#10155](https://github.com/pydantic/pydantic/pull/10155) * Add support for stringified annotations when using `PrivateAttr` with `Annotated` by [@Viicos](https://github.com/Viicos) in [#10157](https://github.com/pydantic/pydantic/pull/10157) * Fix JSON Schema `number` type for literal and enum schemas by [@Viicos](https://github.com/Viicos) in [#10172](https://github.com/pydantic/pydantic/pull/10172) * Fix JSON Schema generation of fields with plain validators in serialization mode by [@Viicos](https://github.com/Viicos) in [#10167](https://github.com/pydantic/pydantic/pull/10167) * Fix invalid JSON Schemas being generated for functions in certain scenarios by [@Viicos](https://github.com/Viicos) in [#10188](https://github.com/pydantic/pydantic/pull/10188) * Make sure generated JSON Schemas are valid in tests by [@Viicos](https://github.com/Viicos) in [#10182](https://github.com/pydantic/pydantic/pull/10182) * Fix key error with custom serializer by [@sydney-runkle](https://github.com/sydney-runkle) in [#10200](https://github.com/pydantic/pydantic/pull/10200) * Add 'wss' for allowed schemes in NatsDsn by [@swelborn](https://github.com/swelborn) in [#10224](https://github.com/pydantic/pydantic/pull/10224) * Fix `Mapping` and `MutableMapping` annotations to use mapping schema instead of dict schema by [@sydney-runkle](https://github.com/sydney-runkle) in [#10020](https://github.com/pydantic/pydantic/pull/10020) * Fix JSON Schema generation for constrained dates by [@Viicos](https://github.com/Viicos) in [#10185](https://github.com/pydantic/pydantic/pull/10185) * Fix discriminated union bug regression when using enums by [@kfreezen](https://github.com/kfreezen) in [pydantic/pydantic-core#1286](https://github.com/pydantic/pydantic-core/pull/1286) * Fix `field_serializer` with computed field when using `*` by [@nix010](https://github.com/nix010) in [pydantic/pydantic-core#1349](https://github.com/pydantic/pydantic-core/pull/1349) * Try each option in `Union` serializer before inference by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1398](https://github.com/pydantic/pydantic-core/pull/1398) * Fix `float` serialization behavior in `strict` mode by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1400](https://github.com/pydantic/pydantic-core/pull/1400) * Introduce `exactness` into Decimal validation logic to improve union validation behavior by [@sydney-runkle](https://github.com/sydney-runkle) in in [pydantic/pydantic-core#1405](https://github.com/pydantic/pydantic-core/pull/1405) * Fix new warnings assertions to use `pytest.warns()` by [@mgorny](https://github.com/mgorny) in [#10241](https://github.com/pydantic/pydantic/pull/10241) * Fix a crash when cleaning the namespace in `ModelMetaclass` by [@Viicos](https://github.com/Viicos) in [#10242](https://github.com/pydantic/pydantic/pull/10242) * Fix parent namespace issue with model rebuilds by [@sydney-runkle](https://github.com/sydney-runkle) in [#10257](https://github.com/pydantic/pydantic/pull/10257) * Remove defaults filter for namespace by [@sydney-runkle](https://github.com/sydney-runkle) in [#10261](https://github.com/pydantic/pydantic/pull/10261) * Use identity instead of equality after validating model in `__init__` by [@Viicos](https://github.com/Viicos) in [#10264](https://github.com/pydantic/pydantic/pull/10264) * Support `BigInt` serialization for `int` subclasses by [@kxx317](https://github.com/kxx317) in [pydantic/pydantic-core#1417](https://github.com/pydantic/pydantic-core/pull/1417) * Support signature for wrap validators without `info` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10277](https://github.com/pydantic/pydantic/pull/10277) * Ensure `__pydantic_complete__` is set when rebuilding `dataclasses` by [@Viicos](https://github.com/Viicos) in [#10291](https://github.com/pydantic/pydantic/pull/10291) * Respect `schema_generator` config value in `TypeAdapter` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10300](https://github.com/pydantic/pydantic/pull/10300) ### New Contributors[¶](#new-contributors_8 "Permanent link") #### `pydantic`[¶](#pydantic "Permanent link") * [@kwint](https://github.com/kwint) made their first contribution in [#9787](https://github.com/pydantic/pydantic/pull/9787) * [@seekinginfiniteloop](https://github.com/seekinginfiniteloop) made their first contribution in [#9822](https://github.com/pydantic/pydantic/pull/9822) * [@a-alexander](https://github.com/a-alexander) made their first contribution in [#9848](https://github.com/pydantic/pydantic/pull/9848) * [@maximilianfellhuber](https://github.com/maximilianfellhuber) made their first contribution in [#9885](https://github.com/pydantic/pydantic/pull/9885) * [@karmaBonfire](https://github.com/karmaBonfire) made their first contribution in [#9945](https://github.com/pydantic/pydantic/pull/9945) * [@s-rigaud](https://github.com/s-rigaud) made their first contribution in [#9958](https://github.com/pydantic/pydantic/pull/9958) * [@msabramo](https://github.com/msabramo) made their first contribution in [#9964](https://github.com/pydantic/pydantic/pull/9964) * [@DimaCybr](https://github.com/DimaCybr) made their first contribution in [#9972](https://github.com/pydantic/pydantic/pull/9972) * [@kc0506](https://github.com/kc0506) made their first contribution in [#9971](https://github.com/pydantic/pydantic/pull/9971) * [@haoyun](https://github.com/haoyun) made their first contribution in [#9990](https://github.com/pydantic/pydantic/pull/9990) * [@radekwlsk](https://github.com/radekwlsk) made their first contribution in [#9938](https://github.com/pydantic/pydantic/pull/9938) * [@dpeachey](https://github.com/dpeachey) made their first contribution in [#10029](https://github.com/pydantic/pydantic/pull/10029) * [@BoxyUwU](https://github.com/BoxyUwU) made their first contribution in [#10085](https://github.com/pydantic/pydantic/pull/10085) * [@mochi22](https://github.com/mochi22) made their first contribution in [#10082](https://github.com/pydantic/pydantic/pull/10082) * [@aditkumar72](https://github.com/aditkumar72) made their first contribution in [#10128](https://github.com/pydantic/pydantic/pull/10128) * [@changhc](https://github.com/changhc) made their first contribution in [#9654](https://github.com/pydantic/pydantic/pull/9654) * [@insumanth](https://github.com/insumanth) made their first contribution in [#10229](https://github.com/pydantic/pydantic/pull/10229) * [@AdolfoVillalobos](https://github.com/AdolfoVillalobos) made their first contribution in [#10240](https://github.com/pydantic/pydantic/pull/10240) * [@bllchmbrs](https://github.com/bllchmbrs) made their first contribution in [#10270](https://github.com/pydantic/pydantic/pull/10270) #### `pydantic-core`[¶](#pydantic-core "Permanent link") * [@kfreezen](https://github.com/kfreezen) made their first contribution in [pydantic/pydantic-core#1286](https://github.com/pydantic/pydantic-core/pull/1286) * [@tinez](https://github.com/tinez) made their first contribution in [pydantic/pydantic-core#1368](https://github.com/pydantic/pydantic-core/pull/1368) * [@fft001](https://github.com/fft001) made their first contribution in [pydantic/pydantic-core#1362](https://github.com/pydantic/pydantic-core/pull/1362) * [@nix010](https://github.com/nix010) made their first contribution in [pydantic/pydantic-core#1349](https://github.com/pydantic/pydantic-core/pull/1349) * [@BoxyUwU](https://github.com/BoxyUwU) made their first contribution in [pydantic/pydantic-core#1379](https://github.com/pydantic/pydantic-core/pull/1379) * [@candleindark](https://github.com/candleindark) made their first contribution in [pydantic/pydantic-core#1404](https://github.com/pydantic/pydantic-core/pull/1404) * [@changhc](https://github.com/changhc) made their first contribution in [pydantic/pydantic-core#1331](https://github.com/pydantic/pydantic-core/pull/1331) v2.9.0b2 (2024-08-30)[¶](#v290b2-2024-08-30 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.9.0b2) for details. v2.9.0b1 (2024-08-26)[¶](#v290b1-2024-08-26 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.9.0b1) for details. v2.8.2 (2024-07-03)[¶](#v282-2024-07-03 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.2) ### What's Changed[¶](#whats-changed_18 "Permanent link") #### Fixes[¶](#fixes_18 "Permanent link") * Fix issue with assertion caused by pluggable schema validator by [@dmontagu](https://github.com/dmontagu) in [#9838](https://github.com/pydantic/pydantic/pull/9838) v2.8.1 (2024-07-03)[¶](#v281-2024-07-03 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.1) ### What's Changed[¶](#whats-changed_19 "Permanent link") #### Packaging[¶](#packaging_10 "Permanent link") * Bump `ruff` to `v0.5.0` and `pyright` to `v1.1.369` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9801](https://github.com/pydantic/pydantic/pull/9801) * Bump `pydantic-core` to `v2.20.1`, `pydantic-extra-types` to `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9832](https://github.com/pydantic/pydantic/pull/9832) #### Fixes[¶](#fixes_19 "Permanent link") * Fix breaking change in `to_snake` from v2.7 -> v2.8 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9812](https://github.com/pydantic/pydantic/pull/9812) * Fix list constraint json schema application by [@sydney-runkle](https://github.com/sydney-runkle) in [#9818](https://github.com/pydantic/pydantic/pull/9818) * Support time duration more than 23 by [@nix010](https://github.com/nix010) in [pydantic/speedate#64](https://github.com/pydantic/speedate/pull/64) * Fix millisecond fraction being handled with the wrong scale by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/speedate#65](https://github.com/pydantic/speedate/pull/65) * Handle negative fractional durations correctly by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/speedate#71](https://github.com/pydantic/speedate/pull/71) v2.8.0 (2024-07-01)[¶](#v280-2024-07-01 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.0) The code released in v2.8.0 is functionally identical to that of v2.8.0b1. ### What's Changed[¶](#whats-changed_20 "Permanent link") #### Packaging[¶](#packaging_11 "Permanent link") * Update citation version automatically with new releases by [@sydney-runkle](https://github.com/sydney-runkle) in [#9673](https://github.com/pydantic/pydantic/pull/9673) * Bump pyright to `v1.1.367` and add type checking tests for pipeline API by [@adriangb](https://github.com/adriangb) in [#9674](https://github.com/pydantic/pydantic/pull/9674) * Update `pydantic.v1` stub to `v1.10.17` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9707](https://github.com/pydantic/pydantic/pull/9707) * General package updates to prep for `v2.8.0b1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9741](https://github.com/pydantic/pydantic/pull/9741) * Bump `pydantic-core` to `v2.20.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9745](https://github.com/pydantic/pydantic/pull/9745) * Add support for Python 3.13 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9743](https://github.com/pydantic/pydantic/pull/9743) * Update `pdm` version used for `pdm.lock` to v2.16.1 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9761](https://github.com/pydantic/pydantic/pull/9761) * Update to `ruff` `v0.4.8` by [@Viicos](https://github.com/Viicos) in [#9585](https://github.com/pydantic/pydantic/pull/9585) #### New Features[¶](#new-features_6 "Permanent link") * Experimental: support `defer_build` for `TypeAdapter` by [@MarkusSintonen](https://github.com/MarkusSintonen) in [#8939](https://github.com/pydantic/pydantic/pull/8939) * Implement `deprecated` field in json schema by [@NeevCohen](https://github.com/NeevCohen) in [#9298](https://github.com/pydantic/pydantic/pull/9298) * Experimental: Add pipeline API by [@adriangb](https://github.com/adriangb) in [#9459](https://github.com/pydantic/pydantic/pull/9459) * Add support for programmatic title generation by [@NeevCohen](https://github.com/NeevCohen) in [#9183](https://github.com/pydantic/pydantic/pull/9183) * Implement `fail_fast` feature by [@uriyyo](https://github.com/uriyyo) in [#9708](https://github.com/pydantic/pydantic/pull/9708) * Add `ser_json_inf_nan='strings'` mode to produce valid JSON by [@josh-newman](https://github.com/josh-newman) in [pydantic/pydantic-core#1307](https://github.com/pydantic/pydantic-core/pull/1307) #### Changes[¶](#changes_4 "Permanent link") * Add warning when "alias" is set in ignored `Annotated` field by [@nix010](https://github.com/nix010) in [#9170](https://github.com/pydantic/pydantic/pull/9170) * Support serialization of some serializable defaults in JSON schema by [@sydney-runkle](https://github.com/sydney-runkle) in [#9624](https://github.com/pydantic/pydantic/pull/9624) * Relax type specification for `__validators__` values in `create_model` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9697](https://github.com/pydantic/pydantic/pull/9697) * **Breaking Change:** Improve `smart` union matching logic by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1322](https://github.com/pydantic/pydantic-core/pull/1322) You can read more about our `smart` union matching logic [here](https://docs.pydantic.dev/dev/concepts/unions/#smart-mode) . 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. #### Performance[¶](#performance_5 "Permanent link") ##### Internal Improvements[¶](#internal-improvements "Permanent link") * ⚡️ Speed up `_display_error_loc()` by 25% in `pydantic/v1/error_wrappers.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9653](https://github.com/pydantic/pydantic/pull/9653) * ⚡️ Speed up `_get_all_json_refs()` by 34% in `pydantic/json_schema.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9650](https://github.com/pydantic/pydantic/pull/9650) * ⚡️ Speed up `is_pydantic_dataclass()` by 41% in `pydantic/dataclasses.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9652](https://github.com/pydantic/pydantic/pull/9652) * ⚡️ Speed up `to_snake()` by 27% in `pydantic/alias_generators.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9747](https://github.com/pydantic/pydantic/pull/9747) * ⚡️ Speed up `unwrap_wrapped_function()` by 93% in `pydantic/_internal/_decorators.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9727](https://github.com/pydantic/pydantic/pull/9727) #### Fixes[¶](#fixes_20 "Permanent link") * Replace `__spec__.parent` with `__package__` by [@hramezani](https://github.com/hramezani) in [#9331](https://github.com/pydantic/pydantic/pull/9331) * Fix Outputted Model JSON Schema for `Sequence` type by [@anesmemisevic](https://github.com/anesmemisevic) in [#9303](https://github.com/pydantic/pydantic/pull/9303) * Fix typing of `_frame_depth` by [@Viicos](https://github.com/Viicos) in [#9353](https://github.com/pydantic/pydantic/pull/9353) * Make `ImportString` json schema compatible by [@amitschang](https://github.com/amitschang) in [#9344](https://github.com/pydantic/pydantic/pull/9344) * Hide private attributes (`PrivateAttr`) from `__init__` signature in type checkers by [@idan22moral](https://github.com/idan22moral) in [#9293](https://github.com/pydantic/pydantic/pull/9293) * Make detection of `TypeVar` defaults robust to the CPython `PEP-696` implementation by [@AlexWaygood](https://github.com/AlexWaygood) in [#9426](https://github.com/pydantic/pydantic/pull/9426) * Fix usage of `PlainSerializer` with builtin types by [@Viicos](https://github.com/Viicos) in [#9450](https://github.com/pydantic/pydantic/pull/9450) * Add more robust custom validation examples by [@ChrisPappalardo](https://github.com/ChrisPappalardo) in [#9468](https://github.com/pydantic/pydantic/pull/9468) * Fix ignored `strict` specification for `StringConstraint(strict=False)` by [@vbmendes](https://github.com/vbmendes) in [#9476](https://github.com/pydantic/pydantic/pull/9476) * **Breaking Change:** Use PEP 570 syntax by [@Viicos](https://github.com/Viicos) in [#9479](https://github.com/pydantic/pydantic/pull/9479) * Use `Self` where possible by [@Viicos](https://github.com/Viicos) in [#9479](https://github.com/pydantic/pydantic/pull/9479) * Do not alter `RootModel.model_construct` signature in the `mypy` plugin by [@Viicos](https://github.com/Viicos) in [#9480](https://github.com/pydantic/pydantic/pull/9480) * Fixed type hint of `validation_context` by [@OhioDschungel6](https://github.com/OhioDschungel6) in [#9508](https://github.com/pydantic/pydantic/pull/9508) * Support context being passed to TypeAdapter's `dump_json`/`dump_python` by [@alexcouper](https://github.com/alexcouper) in [#9495](https://github.com/pydantic/pydantic/pull/9495) * Updates type signature for `Field()` constructor by [@bjmc](https://github.com/bjmc) in [#9484](https://github.com/pydantic/pydantic/pull/9484) * Improve builtin alias generators by [@sydney-runkle](https://github.com/sydney-runkle) in [#9561](https://github.com/pydantic/pydantic/pull/9561) * Fix typing of `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#9570](https://github.com/pydantic/pydantic/pull/9570) * Add fallback default value for private fields in `__setstate__` of BaseModel by [@anhpham1509](https://github.com/anhpham1509) in [#9584](https://github.com/pydantic/pydantic/pull/9584) * Support `PEP 746` by [@adriangb](https://github.com/adriangb) in [#9587](https://github.com/pydantic/pydantic/pull/9587) * Allow validator and serializer functions to have default values by [@Viicos](https://github.com/Viicos) in [#9478](https://github.com/pydantic/pydantic/pull/9478) * Fix bug with mypy plugin's handling of covariant `TypeVar` fields by [@dmontagu](https://github.com/dmontagu) in [#9606](https://github.com/pydantic/pydantic/pull/9606) * Fix multiple annotation / constraint application logic by [@sydney-runkle](https://github.com/sydney-runkle) in [#9623](https://github.com/pydantic/pydantic/pull/9623) * Respect `regex` flags in validation and json schema by [@sydney-runkle](https://github.com/sydney-runkle) in [#9591](https://github.com/pydantic/pydantic/pull/9591) * Fix type hint on `IpvAnyAddress` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9640](https://github.com/pydantic/pydantic/pull/9640) * Allow a field specifier on `__pydantic_extra__` by [@dmontagu](https://github.com/dmontagu) in [#9659](https://github.com/pydantic/pydantic/pull/9659) * Use normalized case for file path comparison by [@sydney-runkle](https://github.com/sydney-runkle) in [#9737](https://github.com/pydantic/pydantic/pull/9737) * Modify constraint application logic to allow field constraints on `Optional[Decimal]` by [@lazyhope](https://github.com/lazyhope) in [#9754](https://github.com/pydantic/pydantic/pull/9754) * `validate_call` type params fix by [@sydney-runkle](https://github.com/sydney-runkle) in [#9760](https://github.com/pydantic/pydantic/pull/9760) * Check all warnings returned by pytest.warns() by [@s-t-e-v-e-n-k](https://github.com/s-t-e-v-e-n-k) in [#9702](https://github.com/pydantic/pydantic/pull/9702) * Reuse `re.Pattern` object in regex patterns to allow for regex flags by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1318](https://github.com/pydantic/pydantic-core/pull/1318) ### New Contributors[¶](#new-contributors_9 "Permanent link") * [@idan22moral](https://github.com/idan22moral) made their first contribution in [#9294](https://github.com/pydantic/pydantic/pull/9294) * [@anesmemisevic](https://github.com/anesmemisevic) made their first contribution in [#9303](https://github.com/pydantic/pydantic/pull/9303) * [@max-muoto](https://github.com/max-muoto) made their first contribution in [#9338](https://github.com/pydantic/pydantic/pull/9338) * [@amitschang](https://github.com/amitschang) made their first contribution in [#9344](https://github.com/pydantic/pydantic/pull/9344) * [@paulmartin91](https://github.com/paulmartin91) made their first contribution in [#9410](https://github.com/pydantic/pydantic/pull/9410) * [@OhioDschungel6](https://github.com/OhioDschungel6) made their first contribution in [#9405](https://github.com/pydantic/pydantic/pull/9405) * [@AlexWaygood](https://github.com/AlexWaygood) made their first contribution in [#9426](https://github.com/pydantic/pydantic/pull/9426) * [@kinuax](https://github.com/kinuax) made their first contribution in [#9433](https://github.com/pydantic/pydantic/pull/9433) * [@antoni-jamiolkowski](https://github.com/antoni-jamiolkowski) made their first contribution in [#9431](https://github.com/pydantic/pydantic/pull/9431) * [@candleindark](https://github.com/candleindark) made their first contribution in [#9448](https://github.com/pydantic/pydantic/pull/9448) * [@nix010](https://github.com/nix010) made their first contribution in [#9170](https://github.com/pydantic/pydantic/pull/9170) * [@tomy0000000](https://github.com/tomy0000000) made their first contribution in [#9457](https://github.com/pydantic/pydantic/pull/9457) * [@vbmendes](https://github.com/vbmendes) made their first contribution in [#9470](https://github.com/pydantic/pydantic/pull/9470) * [@micheleAlberto](https://github.com/micheleAlberto) made their first contribution in [#9471](https://github.com/pydantic/pydantic/pull/9471) * [@ChrisPappalardo](https://github.com/ChrisPappalardo) made their first contribution in [#9468](https://github.com/pydantic/pydantic/pull/9468) * [@blueTurtz](https://github.com/blueTurtz) made their first contribution in [#9475](https://github.com/pydantic/pydantic/pull/9475) * [@WinterBlue16](https://github.com/WinterBlue16) made their first contribution in [#9477](https://github.com/pydantic/pydantic/pull/9477) * [@bittner](https://github.com/bittner) made their first contribution in [#9500](https://github.com/pydantic/pydantic/pull/9500) * [@alexcouper](https://github.com/alexcouper) made their first contribution in [#9495](https://github.com/pydantic/pydantic/pull/9495) * [@bjmc](https://github.com/bjmc) made their first contribution in [#9484](https://github.com/pydantic/pydantic/pull/9484) * [@pjvv](https://github.com/pjvv) made their first contribution in [#9529](https://github.com/pydantic/pydantic/pull/9529) * [@nedbat](https://github.com/nedbat) made their first contribution in [#9530](https://github.com/pydantic/pydantic/pull/9530) * [@gunnellEvan](https://github.com/gunnellEvan) made their first contribution in [#9469](https://github.com/pydantic/pydantic/pull/9469) * [@jaymbans](https://github.com/jaymbans) made their first contribution in [#9531](https://github.com/pydantic/pydantic/pull/9531) * [@MarcBresson](https://github.com/MarcBresson) made their first contribution in [#9534](https://github.com/pydantic/pydantic/pull/9534) * [@anhpham1509](https://github.com/anhpham1509) made their first contribution in [#9584](https://github.com/pydantic/pydantic/pull/9584) * [@K-dash](https://github.com/K-dash) made their first contribution in [#9595](https://github.com/pydantic/pydantic/pull/9595) * [@s-t-e-v-e-n-k](https://github.com/s-t-e-v-e-n-k) made their first contribution in [#9527](https://github.com/pydantic/pydantic/pull/9527) * [@airwoodix](https://github.com/airwoodix) made their first contribution in [#9506](https://github.com/pydantic/pydantic/pull/9506) * [@misrasaurabh1](https://github.com/misrasaurabh1) made their first contribution in [#9653](https://github.com/pydantic/pydantic/pull/9653) * [@AlessandroMiola](https://github.com/AlessandroMiola) made their first contribution in [#9740](https://github.com/pydantic/pydantic/pull/9740) * [@mylapallilavanyaa](https://github.com/mylapallilavanyaa) made their first contribution in [#9746](https://github.com/pydantic/pydantic/pull/9746) * [@lazyhope](https://github.com/lazyhope) made their first contribution in [#9754](https://github.com/pydantic/pydantic/pull/9754) * [@YassinNouh21](https://github.com/YassinNouh21) made their first contribution in [#9759](https://github.com/pydantic/pydantic/pull/9759) v2.8.0b1 (2024-06-27)[¶](#v280b1-2024-06-27 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.0b1) for details. v2.7.4 (2024-06-12)[¶](#v274-2024-06-12 "Permanent link") ---------------------------------------------------------- [Github release](https://github.com/pydantic/pydantic/releases/tag/v2.7.4) ### What's Changed[¶](#whats-changed_21 "Permanent link") #### Packaging[¶](#packaging_12 "Permanent link") * Bump `pydantic.v1` to `v1.10.16` reference by [@sydney-runkle](https://github.com/sydney-runkle) in [#9639](https://github.com/pydantic/pydantic/pull/9639) #### Fixes[¶](#fixes_21 "Permanent link") * Specify `recursive_guard` as kwarg in `FutureRef._evaluate` by [@vfazio](https://github.com/vfazio) in [#9612](https://github.com/pydantic/pydantic/pull/9612) v2.7.3 (2024-06-03)[¶](#v273-2024-06-03 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.3) ### What's Changed[¶](#whats-changed_22 "Permanent link") #### Packaging[¶](#packaging_13 "Permanent link") * Bump `pydantic-core` to `v2.18.4` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9550](https://github.com/pydantic/pydantic/pull/9550) #### Fixes[¶](#fixes_22 "Permanent link") * Fix u style unicode strings in python [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#110](https://github.com/pydantic/jiter/pull/110) v2.7.2 (2024-05-28)[¶](#v272-2024-05-28 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.2) ### What's Changed[¶](#whats-changed_23 "Permanent link") #### Packaging[¶](#packaging_14 "Permanent link") * Bump `pydantic-core` to `v2.18.3` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9515](https://github.com/pydantic/pydantic/pull/9515) #### Fixes[¶](#fixes_23 "Permanent link") * Replace `__spec__.parent` with `__package__` by [@hramezani](https://github.com/hramezani) in [#9331](https://github.com/pydantic/pydantic/pull/9331) * Fix validation of `int`s with leading unary minus by [@RajatRajdeep](https://github.com/RajatRajdeep) in [pydantic/pydantic-core#1291](https://github.com/pydantic/pydantic-core/pull/1291) * Fix `str` subclass validation for enums by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1273](https://github.com/pydantic/pydantic-core/pull/1273) * Support `BigInt`s in `Literal`s and `Enum`s by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1297](https://github.com/pydantic/pydantic-core/pull/1297) * Fix: uuid - allow `str` subclass as input by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1296](https://github.com/pydantic/pydantic-core/pull/1296) v2.7.1 (2024-04-23)[¶](#v271-2024-04-23 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.1) ### What's Changed[¶](#whats-changed_24 "Permanent link") #### Packaging[¶](#packaging_15 "Permanent link") * Bump `pydantic-core` to `v2.18.2` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9307](https://github.com/pydantic/pydantic/pull/9307) #### New Features[¶](#new-features_7 "Permanent link") * Ftp and Websocket connection strings support by [@CherrySuryp](https://github.com/CherrySuryp) in [#9205](https://github.com/pydantic/pydantic/pull/9205) #### Changes[¶](#changes_5 "Permanent link") * Use field description for RootModel schema description when there is `…` by [@LouisGobert](https://github.com/LouisGobert) in [#9214](https://github.com/pydantic/pydantic/pull/9214) #### Fixes[¶](#fixes_24 "Permanent link") * Fix `validation_alias` behavior with `model_construct` for `AliasChoices` and `AliasPath` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9223](https://github.com/pydantic/pydantic/pull/9223) * Revert `typing.Literal` and import it outside the TYPE\_CHECKING block by [@frost-nzcr4](https://github.com/frost-nzcr4) in [#9232](https://github.com/pydantic/pydantic/pull/9232) * Fix `Secret` serialization schema, applicable for unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#9240](https://github.com/pydantic/pydantic/pull/9240) * Fix `strict` application to `function-after` with `use_enum_values` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9279](https://github.com/pydantic/pydantic/pull/9279) * Address case where `model_construct` on a class which defines `model_post_init` fails with `AttributeError` by [@babygrimes](https://github.com/babygrimes) in [#9168](https://github.com/pydantic/pydantic/pull/9168) * Fix `model_json_schema` with config types by [@NeevCohen](https://github.com/NeevCohen) in [#9287](https://github.com/pydantic/pydantic/pull/9287) * Support multiple zeros as an `int` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1269](https://github.com/pydantic/pydantic-core/pull/1269) * Fix validation of `int`s with leading unary plus by [@cknv](https://github.com/cknv) in [pydantic/pydantic-core#1272](https://github.com/pydantic/pydantic-core/pull/1272) * Fix interaction between `extra != 'ignore'` and `from_attributes=True` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1276](https://github.com/pydantic/pydantic-core/pull/1276) * Handle error from `Enum`'s `missing` function as `ValidationError` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1274](https://github.com/pydantic/pydantic-core/pull/1754) * Fix memory leak with `Iterable` validation by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1271](https://github.com/pydantic/pydantic-core/pull/1751) ### New Contributors[¶](#new-contributors_10 "Permanent link") * [@zzstoatzz](https://github.com/zzstoatzz) made their first contribution in [#9219](https://github.com/pydantic/pydantic/pull/9219) * [@frost-nzcr4](https://github.com/frost-nzcr4) made their first contribution in [#9232](https://github.com/pydantic/pydantic/pull/9232) * [@CherrySuryp](https://github.com/CherrySuryp) made their first contribution in [#9205](https://github.com/pydantic/pydantic/pull/9205) * [@vagenas](https://github.com/vagenas) made their first contribution in [#9268](https://github.com/pydantic/pydantic/pull/9268) * [@ollz272](https://github.com/ollz272) made their first contribution in [#9262](https://github.com/pydantic/pydantic/pull/9262) * [@babygrimes](https://github.com/babygrimes) made their first contribution in [#9168](https://github.com/pydantic/pydantic/pull/9168) * [@swelborn](https://github.com/swelborn) made their first contribution in [#9296](https://github.com/pydantic/pydantic/pull/9296) * [@kf-novi](https://github.com/kf-novi) made their first contribution in [#9236](https://github.com/pydantic/pydantic/pull/9236) * [@lgeiger](https://github.com/lgeiger) made their first contribution in [#9288](https://github.com/pydantic/pydantic/pull/9288) v2.7.0 (2024-04-11)[¶](#v270-2024-04-11 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.0) The code released in v2.7.0 is practically identical to that of v2.7.0b1. ### What's Changed[¶](#whats-changed_25 "Permanent link") #### Packaging[¶](#packaging_16 "Permanent link") * Reorganize `pyproject.toml` sections by [@Viicos](https://github.com/Viicos) in [#8899](https://github.com/pydantic/pydantic/pull/8899) * Bump `pydantic-core` to `v2.18.1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9211](https://github.com/pydantic/pydantic/pull/9211) * Adopt `jiter` `v0.2.0` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1250](https://github.com/pydantic/pydantic-core/pull/1250) #### New Features[¶](#new-features_8 "Permanent link") * Extract attribute docstrings from `FieldInfo.description` by [@Viicos](https://github.com/Viicos) in [#6563](https://github.com/pydantic/pydantic/pull/6563) * Add a `with_config` decorator to comply with typing spec by [@Viicos](https://github.com/Viicos) in [#8611](https://github.com/pydantic/pydantic/pull/8611) * Allow an optional separator splitting the value and unit of the result of `ByteSize.human_readable` by [@jks15satoshi](https://github.com/jks15satoshi) in [#8706](https://github.com/pydantic/pydantic/pull/8706) * Add generic `Secret` base type by [@conradogarciaberrotaran](https://github.com/conradogarciaberrotaran) in [#8519](https://github.com/pydantic/pydantic/pull/8519) * Make use of `Sphinx` inventories for cross references in docs by [@Viicos](https://github.com/Viicos) in [#8682](https://github.com/pydantic/pydantic/pull/8682) * Add environment variable to disable plugins by [@geospackle](https://github.com/geospackle) in [#8767](https://github.com/pydantic/pydantic/pull/8767) * Add support for `deprecated` fields by [@Viicos](https://github.com/Viicos) in [#8237](https://github.com/pydantic/pydantic/pull/8237) * Allow `field_serializer('*')` by [@ornariece](https://github.com/ornariece) in [#9001](https://github.com/pydantic/pydantic/pull/9001) * Handle a case when `model_config` is defined as a model property by [@alexeyt101](https://github.com/alexeyt101) in [#9004](https://github.com/pydantic/pydantic/pull/9004) * Update `create_model()` to support `typing.Annotated` as input by [@wannieman98](https://github.com/wannieman98) in [#8947](https://github.com/pydantic/pydantic/pull/8947) * Add `ClickhouseDsn` support by [@solidguy7](https://github.com/solidguy7) in [#9062](https://github.com/pydantic/pydantic/pull/9062) * Add support for `re.Pattern[str]` to `pattern` field by [@jag-k](https://github.com/jag-k) in [#9053](https://github.com/pydantic/pydantic/pull/9053) * Support for `serialize_as_any` runtime setting by [@sydney-runkle](https://github.com/sydney-runkle) in [#8830](https://github.com/pydantic/pydantic/pull/8830) * Add support for `typing.Self` by [@Youssefares](https://github.com/Youssefares) in [#9023](https://github.com/pydantic/pydantic/pull/9023) * Ability to pass `context` to serialization by [@ornariece](https://github.com/ornariece) in [#8965](https://github.com/pydantic/pydantic/pull/8965) * Add feedback widget to docs with flarelytics integration by [@sydney-runkle](https://github.com/sydney-runkle) in [#9129](https://github.com/pydantic/pydantic/pull/9129) * Support for parsing partial JSON strings in Python by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#66](https://github.com/pydantic/jiter/pull/66) **Finalized in v2.7.0, rather than v2.7.0b1:** \* Add support for field level number to str coercion option by [@NeevCohen](https://github.com/NeevCohen) in [#9137](https://github.com/pydantic/pydantic/pull/9137) \* Update `warnings` parameter for serialization utilities to allow raising a warning by [@Lance-Drane](https://github.com/Lance-Drane) in [#9166](https://github.com/pydantic/pydantic/pull/9166) #### Changes[¶](#changes_6 "Permanent link") * Correct docs, logic for `model_construct` behavior with `extra` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8807](https://github.com/pydantic/pydantic/pull/8807) * Improve error message for improper `RootModel` subclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8857](https://github.com/pydantic/pydantic/pull/8857) * **Breaking Change:** Use `PEP570` syntax by [@Viicos](https://github.com/Viicos) in [#8940](https://github.com/pydantic/pydantic/pull/8940) * Add `enum` and `type` to the JSON schema for single item literals by [@dmontagu](https://github.com/dmontagu) in [#8944](https://github.com/pydantic/pydantic/pull/8944) * Deprecate `update_json_schema` internal function by [@sydney-runkle](https://github.com/sydney-runkle) in [#9125](https://github.com/pydantic/pydantic/pull/9125) * Serialize duration to hour minute second, instead of just seconds by [@kakilangit](https://github.com/kakilangit) in [pydantic/speedate#50](https://github.com/pydantic/speedate/pull/50) * Trimming str before parsing to int and float by [@hungtsetse](https://github.com/hungtsetse) in [pydantic/pydantic-core#1203](https://github.com/pydantic/pydantic-core/pull/1203) #### Performance[¶](#performance_6 "Permanent link") * `enum` validator improvements by [@samuelcolvin](https://github.com/samuelcolvin) in [#9045](https://github.com/pydantic/pydantic/pull/9045) * Move `enum` validation and serialization to Rust by [@samuelcolvin](https://github.com/samuelcolvin) in [#9064](https://github.com/pydantic/pydantic/pull/9064) * Improve schema generation for nested dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#9114](https://github.com/pydantic/pydantic/pull/9114) * Fast path for ASCII python string creation in JSON by [@samuelcolvin](https://github.com/samuelcolvin) in in [pydantic/jiter#72](https://github.com/pydantic/jiter/pull/72) * SIMD integer and string JSON parsing on `aarch64`(**Note:** SIMD on x86 will be implemented in a future release) by [@samuelcolvin](https://github.com/samuelcolvin) in in [pydantic/jiter#65](https://github.com/pydantic/jiter/pull/65) * Support JSON `Cow` from `jiter` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1231](https://github.com/pydantic/pydantic-core/pull/1231) * MAJOR performance improvement: update to PyO3 0.21 final by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1248](https://github.com/pydantic/pydantic-core/pull/1248) * cache Python strings by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1240](https://github.com/pydantic/pydantic-core/pull/1240) #### Fixes[¶](#fixes_25 "Permanent link") * Fix strict parsing for some `Sequence`s by [@sydney-runkle](https://github.com/sydney-runkle) in [#8614](https://github.com/pydantic/pydantic/pull/8614) * Add a check on the existence of `__qualname__` by [@anci3ntr0ck](https://github.com/anci3ntr0ck) in [#8642](https://github.com/pydantic/pydantic/pull/8642) * Handle `__pydantic_extra__` annotation being a string or inherited by [@alexmojaki](https://github.com/alexmojaki) in [#8659](https://github.com/pydantic/pydantic/pull/8659) * Fix json validation for `NameEmail` by [@Holi0317](https://github.com/Holi0317) in [#8650](https://github.com/pydantic/pydantic/pull/8650) * Fix type-safety of attribute access in `BaseModel` by [@bluenote10](https://github.com/bluenote10) in [#8651](https://github.com/pydantic/pydantic/pull/8651) * Fix bug with `mypy` plugin and `no_strict_optional = True` by [@dmontagu](https://github.com/dmontagu) in [#8666](https://github.com/pydantic/pydantic/pull/8666) * Fix `ByteSize` error `type` change by [@sydney-runkle](https://github.com/sydney-runkle) in [#8681](https://github.com/pydantic/pydantic/pull/8681) * Fix inheriting annotations in dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8679](https://github.com/pydantic/pydantic/pull/8679) * Fix regression in core schema generation for indirect definition references by [@dmontagu](https://github.com/dmontagu) in [#8702](https://github.com/pydantic/pydantic/pull/8702) * Fix unsupported types bug with plain validator by [@sydney-runkle](https://github.com/sydney-runkle) in [#8710](https://github.com/pydantic/pydantic/pull/8710) * Reverting problematic fix from 2.6 release, fixing schema building bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8718](https://github.com/pydantic/pydantic/pull/8718) * fixes `__pydantic_config__` ignored for TypeDict by [@13sin](https://github.com/13sin) in [#8734](https://github.com/pydantic/pydantic/pull/8734) * Fix test failures with `pytest v8.0.0` due to `pytest.warns()` starting to work inside `pytest.raises()` by [@mgorny](https://github.com/mgorny) in [#8678](https://github.com/pydantic/pydantic/pull/8678) * Use `is_valid_field` from 1.x for `mypy` plugin by [@DanielNoord](https://github.com/DanielNoord) in [#8738](https://github.com/pydantic/pydantic/pull/8738) * Better-support `mypy` strict equality flag by [@dmontagu](https://github.com/dmontagu) in [#8799](https://github.com/pydantic/pydantic/pull/8799) * model\_json\_schema export with Annotated types misses 'required' parameters by [@LouisGobert](https://github.com/LouisGobert) in [#8793](https://github.com/pydantic/pydantic/pull/8793) * Fix default inclusion in `FieldInfo.__repr_args__` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8801](https://github.com/pydantic/pydantic/pull/8801) * Fix resolution of forward refs in dataclass base classes that are not present in the subclass module namespace by [@matsjoyce-refeyn](https://github.com/matsjoyce-refeyn) in [#8751](https://github.com/pydantic/pydantic/pull/8751) * Fix `BaseModel` type annotations to be resolvable by `typing.get_type_hints` by [@devmonkey22](https://github.com/devmonkey22) in [#7680](https://github.com/pydantic/pydantic/pull/7680) * Fix: allow empty string aliases with `AliasGenerator` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8810](https://github.com/pydantic/pydantic/pull/8810) * Fix test along with `date` -> `datetime` timezone assumption fix by [@sydney-runkle](https://github.com/sydney-runkle) in [#8823](https://github.com/pydantic/pydantic/pull/8823) * Fix deprecation warning with usage of `ast.Str` by [@Viicos](https://github.com/Viicos) in [#8837](https://github.com/pydantic/pydantic/pull/8837) * Add missing `deprecated` decorators by [@Viicos](https://github.com/Viicos) in [#8877](https://github.com/pydantic/pydantic/pull/8877) * Fix serialization of `NameEmail` if name includes an email address by [@NeevCohen](https://github.com/NeevCohen) in [#8860](https://github.com/pydantic/pydantic/pull/8860) * Add information about class in error message of schema generation by [@Czaki](https://github.com/Czaki) in [#8917](https://github.com/pydantic/pydantic/pull/8917) * Make `TypeAdapter`'s typing compatible with special forms by [@adriangb](https://github.com/adriangb) in [#8923](https://github.com/pydantic/pydantic/pull/8923) * Fix issue with config behavior being baked into the ref schema for `enum`s by [@dmontagu](https://github.com/dmontagu) in [#8920](https://github.com/pydantic/pydantic/pull/8920) * More helpful error re wrong `model_json_schema` usage by [@sydney-runkle](https://github.com/sydney-runkle) in [#8928](https://github.com/pydantic/pydantic/pull/8928) * Fix nested discriminated union schema gen, pt 2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8932](https://github.com/pydantic/pydantic/pull/8932) * Fix schema build for nested dataclasses / TypedDicts with discriminators by [@sydney-runkle](https://github.com/sydney-runkle) in [#8950](https://github.com/pydantic/pydantic/pull/8950) * Remove unnecessary logic for definitions schema gen with discriminated unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#8951](https://github.com/pydantic/pydantic/pull/8951) * Fix handling of optionals in `mypy` plugin by [@dmontagu](https://github.com/dmontagu) in [#9008](https://github.com/pydantic/pydantic/pull/9008) * Fix `PlainSerializer` usage with std type constructor by [@sydney-runkle](https://github.com/sydney-runkle) in [#9031](https://github.com/pydantic/pydantic/pull/9031) * Remove unnecessary warning for config in plugin by [@dmontagu](https://github.com/dmontagu) in [#9039](https://github.com/pydantic/pydantic/pull/9039) * Fix default value serializing by [@NeevCohen](https://github.com/NeevCohen) in [#9066](https://github.com/pydantic/pydantic/pull/9066) * Fix extra fields check in `Model.__getattr__()` by [@NeevCohen](https://github.com/NeevCohen) in [#9082](https://github.com/pydantic/pydantic/pull/9082) * Fix `ClassVar` forward ref inherited from parent class by [@alexmojaki](https://github.com/alexmojaki) in [#9097](https://github.com/pydantic/pydantic/pull/9097) * fix sequence like validator with strict `True` by [@andresliszt](https://github.com/andresliszt) in [#8977](https://github.com/pydantic/pydantic/pull/8977) * Improve warning message when a field name shadows a field in a parent model by [@chan-vince](https://github.com/chan-vince) in [#9105](https://github.com/pydantic/pydantic/pull/9105) * Do not warn about shadowed fields if they are not redefined in a child class by [@chan-vince](https://github.com/chan-vince) in [#9111](https://github.com/pydantic/pydantic/pull/9111) * Fix discriminated union bug with unsubstituted type var by [@sydney-runkle](https://github.com/sydney-runkle) in [#9124](https://github.com/pydantic/pydantic/pull/9124) * Support serialization of `deque` when passed to `Sequence[blah blah blah]` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9128](https://github.com/pydantic/pydantic/pull/9128) * Init private attributes from super-types in `model_post_init` by [@Viicos](https://github.com/Viicos) in [#9134](https://github.com/pydantic/pydantic/pull/9134) * fix `model_construct` with `validation_alias` by [@ornariece](https://github.com/ornariece) in [#9144](https://github.com/pydantic/pydantic/pull/9144) * Ensure json-schema generator handles `Literal` `null` types by [@bruno-f-cruz](https://github.com/bruno-f-cruz) in [#9135](https://github.com/pydantic/pydantic/pull/9135) * **Fixed in v2.7.0**: Fix allow extra generic by [@dmontagu](https://github.com/dmontagu) in [#9193](https://github.com/pydantic/pydantic/pull/9193) ### New Contributors[¶](#new-contributors_11 "Permanent link") * [@hungtsetse](https://github.com/hungtsetse) made their first contribution in [#8546](https://github.com/pydantic/pydantic/pull/8546) * [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) made their first contribution in [#8583](https://github.com/pydantic/pydantic/pull/8583) * [@anci3ntr0ck](https://github.com/anci3ntr0ck) made their first contribution in [#8642](https://github.com/pydantic/pydantic/pull/8642) * [@Holi0317](https://github.com/Holi0317) made their first contribution in [#8650](https://github.com/pydantic/pydantic/pull/8650) * [@bluenote10](https://github.com/bluenote10) made their first contribution in [#8651](https://github.com/pydantic/pydantic/pull/8651) * [@ADSteele916](https://github.com/ADSteele916) made their first contribution in [#8703](https://github.com/pydantic/pydantic/pull/8703) * [@musicinmybrain](https://github.com/musicinmybrain) made their first contribution in [#8731](https://github.com/pydantic/pydantic/pull/8731) * [@jks15satoshi](https://github.com/jks15satoshi) made their first contribution in [#8706](https://github.com/pydantic/pydantic/pull/8706) * [@13sin](https://github.com/13sin) made their first contribution in [#8734](https://github.com/pydantic/pydantic/pull/8734) * [@DanielNoord](https://github.com/DanielNoord) made their first contribution in [#8738](https://github.com/pydantic/pydantic/pull/8738) * [@conradogarciaberrotaran](https://github.com/conradogarciaberrotaran) made their first contribution in [#8519](https://github.com/pydantic/pydantic/pull/8519) * [@chris-griffin](https://github.com/chris-griffin) made their first contribution in [#8775](https://github.com/pydantic/pydantic/pull/8775) * [@LouisGobert](https://github.com/LouisGobert) made their first contribution in [#8793](https://github.com/pydantic/pydantic/pull/8793) * [@matsjoyce-refeyn](https://github.com/matsjoyce-refeyn) made their first contribution in [#8751](https://github.com/pydantic/pydantic/pull/8751) * [@devmonkey22](https://github.com/devmonkey22) made their first contribution in [#7680](https://github.com/pydantic/pydantic/pull/7680) * [@adamency](https://github.com/adamency) made their first contribution in [#8847](https://github.com/pydantic/pydantic/pull/8847) * [@MamfTheKramf](https://github.com/MamfTheKramf) made their first contribution in [#8851](https://github.com/pydantic/pydantic/pull/8851) * [@ornariece](https://github.com/ornariece) made their first contribution in [#9001](https://github.com/pydantic/pydantic/pull/9001) * [@alexeyt101](https://github.com/alexeyt101) made their first contribution in [#9004](https://github.com/pydantic/pydantic/pull/9004) * [@wannieman98](https://github.com/wannieman98) made their first contribution in [#8947](https://github.com/pydantic/pydantic/pull/8947) * [@solidguy7](https://github.com/solidguy7) made their first contribution in [#9062](https://github.com/pydantic/pydantic/pull/9062) * [@kloczek](https://github.com/kloczek) made their first contribution in [#9047](https://github.com/pydantic/pydantic/pull/9047) * [@jag-k](https://github.com/jag-k) made their first contribution in [#9053](https://github.com/pydantic/pydantic/pull/9053) * [@priya-gitTest](https://github.com/priya-gitTest) made their first contribution in [#9088](https://github.com/pydantic/pydantic/pull/9088) * [@Youssefares](https://github.com/Youssefares) made their first contribution in [#9023](https://github.com/pydantic/pydantic/pull/9023) * [@chan-vince](https://github.com/chan-vince) made their first contribution in [#9105](https://github.com/pydantic/pydantic/pull/9105) * [@bruno-f-cruz](https://github.com/bruno-f-cruz) made their first contribution in [#9135](https://github.com/pydantic/pydantic/pull/9135) * [@Lance-Drane](https://github.com/Lance-Drane) made their first contribution in [#9166](https://github.com/pydantic/pydantic/pull/9166) v2.7.0b1 (2024-04-03)[¶](#v270b1-2024-04-03 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.0b1) for details. v2.6.4 (2024-03-12)[¶](#v264-2024-03-12 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.4) ### What's Changed[¶](#whats-changed_26 "Permanent link") #### Fixes[¶](#fixes_26 "Permanent link") * Fix usage of `AliasGenerator` with `computed_field` decorator by [@sydney-runkle](https://github.com/sydney-runkle) in [#8806](https://github.com/pydantic/pydantic/pull/8806) * Fix nested discriminated union schema gen, pt 2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8932](https://github.com/pydantic/pydantic/pull/8932) * Fix bug with no\_strict\_optional=True caused by API deferral by [@dmontagu](https://github.com/dmontagu) in [#8826](https://github.com/pydantic/pydantic/pull/8826) v2.6.3 (2024-02-27)[¶](#v263-2024-02-27 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.3) ### What's Changed[¶](#whats-changed_27 "Permanent link") #### Packaging[¶](#packaging_17 "Permanent link") * Update `pydantic-settings` version in the docs by [@hramezani](https://github.com/hramezani) in [#8906](https://github.com/pydantic/pydantic/pull/8906) #### Fixes[¶](#fixes_27 "Permanent link") * Fix discriminated union schema gen bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8904](https://github.com/pydantic/pydantic/pull/8904) v2.6.2 (2024-02-23)[¶](#v262-2024-02-23 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.2) ### What's Changed[¶](#whats-changed_28 "Permanent link") #### Packaging[¶](#packaging_18 "Permanent link") * Upgrade to `pydantic-core` 2.16.3 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8879](https://github.com/pydantic/pydantic/pull/8879) #### Fixes[¶](#fixes_28 "Permanent link") * 'YYYY-MM-DD' date string coerced to datetime shouldn't infer timezone by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1193](https://github.com/pydantic/pydantic-core/pull/1193) v2.6.1 (2024-02-05)[¶](#v261-2024-02-05 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.1) ### What's Changed[¶](#whats-changed_29 "Permanent link") #### Packaging[¶](#packaging_19 "Permanent link") * Upgrade to `pydantic-core` 2.16.2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8717](https://github.com/pydantic/pydantic/pull/8717) #### Fixes[¶](#fixes_29 "Permanent link") * Fix bug with `mypy` plugin and `no_strict_optional = True` by [@dmontagu](https://github.com/dmontagu) in [#8666](https://github.com/pydantic/pydantic/pull/8666) * Fix `ByteSize` error `type` change by [@sydney-runkle](https://github.com/sydney-runkle) in [#8681](https://github.com/pydantic/pydantic/pull/8681) * Fix inheriting `Field` annotations in dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8679](https://github.com/pydantic/pydantic/pull/8679) * Fix regression in core schema generation for indirect definition references by [@dmontagu](https://github.com/dmontagu) in [#8702](https://github.com/pydantic/pydantic/pull/8702) * Fix unsupported types bug with `PlainValidator` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8710](https://github.com/pydantic/pydantic/pull/8710) * Reverting problematic fix from 2.6 release, fixing schema building bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8718](https://github.com/pydantic/pydantic/pull/8718) * Fix warning for tuple of wrong size in `Union` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1174](https://github.com/pydantic/pydantic-core/pull/1174) * Fix `computed_field` JSON serializer `exclude_none` behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1187](https://github.com/pydantic/pydantic-core/pull/1187) v2.6.0 (2024-01-23)[¶](#v260-2024-01-23 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.0) The code released in v2.6.0 is practically identical to that of v2.6.0b1. ### What's Changed[¶](#whats-changed_30 "Permanent link") #### Packaging[¶](#packaging_20 "Permanent link") * Check for `email-validator` version >= 2.0 by [@commonism](https://github.com/commonism) in [#6033](https://github.com/pydantic/pydantic/pull/6033) * Upgrade \`ruff\`\` target version to Python 3.8 by [@Elkiwa](https://github.com/Elkiwa) in [#8341](https://github.com/pydantic/pydantic/pull/8341) * Update to `pydantic-extra-types==2.4.1` by [@yezz123](https://github.com/yezz123) in [#8478](https://github.com/pydantic/pydantic/pull/8478) * Update to `pyright==1.1.345` by [@Viicos](https://github.com/Viicos) in [#8453](https://github.com/pydantic/pydantic/pull/8453) * Update pydantic-core from 2.14.6 to 2.16.1, significant changes from these updates are described below, full changelog [here](https://github.com/pydantic/pydantic-core/compare/v2.14.6...v2.16.1) #### New Features[¶](#new-features_9 "Permanent link") * Add `NatsDsn` by [@ekeew](https://github.com/ekeew) in [#6874](https://github.com/pydantic/pydantic/pull/6874) * Add `ConfigDict.ser_json_inf_nan` by [@davidhewitt](https://github.com/davidhewitt) in [#8159](https://github.com/pydantic/pydantic/pull/8159) * Add `types.OnErrorOmit` by [@adriangb](https://github.com/adriangb) in [#8222](https://github.com/pydantic/pydantic/pull/8222) * Support `AliasGenerator` usage by [@sydney-runkle](https://github.com/sydney-runkle) in [#8282](https://github.com/pydantic/pydantic/pull/8282) * Add Pydantic People Page to docs by [@sydney-runkle](https://github.com/sydney-runkle) in [#8345](https://github.com/pydantic/pydantic/pull/8345) * Support `yyyy-MM-DD` datetime parsing by [@sydney-runkle](https://github.com/sydney-runkle) in [#8404](https://github.com/pydantic/pydantic/pull/8404) * Added bits conversions to the `ByteSize` class #8415 by [@luca-matei](https://github.com/luca-matei) in [#8507](https://github.com/pydantic/pydantic/pull/8507) * Enable json schema creation with type `ByteSize` by [@geospackle](https://github.com/geospackle) in [#8537](https://github.com/pydantic/pydantic/pull/8537) * Add `eval_type_backport` to handle union operator and builtin generic subscripting in older Pythons by [@alexmojaki](https://github.com/alexmojaki) in [#8209](https://github.com/pydantic/pydantic/pull/8209) * Add support for `dataclass` fields `init` by [@dmontagu](https://github.com/dmontagu) in [#8552](https://github.com/pydantic/pydantic/pull/8552) * Implement pickling for `ValidationError` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1119](https://github.com/pydantic/pydantic-core/pull/1119) * Add unified tuple validator that can handle "variadic" tuples via PEP-646 by [@dmontagu](https://github.com/dmontagu) in [pydantic/pydantic-core#865](https://github.com/pydantic/pydantic-core/pull/865) #### Changes[¶](#changes_7 "Permanent link") * Drop Python3.7 support by [@hramezani](https://github.com/hramezani) in [#7188](https://github.com/pydantic/pydantic/pull/7188) * Drop Python 3.7, and PyPy 3.7 and 3.8 by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1129](https://github.com/pydantic/pydantic-core/pull/1129) * Use positional-only `self` in `BaseModel` constructor, so no field name can ever conflict with it by [@ariebovenberg](https://github.com/ariebovenberg) in [#8072](https://github.com/pydantic/pydantic/pull/8072) * Make `@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](https://github.com/alexmojaki) in [#8268](https://github.com/pydantic/pydantic/pull/8268) * Exclude `BaseModel` docstring from JSON schema description by [@sydney-runkle](https://github.com/sydney-runkle) in [#8352](https://github.com/pydantic/pydantic/pull/8352) * Introducing `classproperty` decorator for `model_computed_fields` by [@Jocelyn-Gas](https://github.com/Jocelyn-Gas) in [#8437](https://github.com/pydantic/pydantic/pull/8437) * Explicitly raise an error if field names clashes with types by [@Viicos](https://github.com/Viicos) in [#8243](https://github.com/pydantic/pydantic/pull/8243) * Use stricter serializer for unions of simple types by [@alexdrydew](https://github.com/alexdrydew) [pydantic/pydantic-core#1132](https://github.com/pydantic/pydantic-core/pull/1132) #### Performance[¶](#performance_7 "Permanent link") * Add Codspeed profiling Actions workflow by [@lambertsbennett](https://github.com/lambertsbennett) in [#8054](https://github.com/pydantic/pydantic/pull/8054) * Improve `int` extraction by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1155](https://github.com/pydantic/pydantic-core/pull/1155) * Improve performance of recursion guard by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1156](https://github.com/pydantic/pydantic-core/pull/1156) * `dataclass` serialization speedups by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1162](https://github.com/pydantic/pydantic-core/pull/1162) * Avoid `HashMap` creation when looking up small JSON objects in `LazyIndexMaps` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#55](https://github.com/pydantic/jiter/pull/55) * use hashbrown to speedup python string caching by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/jiter#51](https://github.com/pydantic/jiter/pull/51) * Replace `Peak` with more efficient `Peek` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/jiter#48](https://github.com/pydantic/jiter/pull/48) #### Fixes[¶](#fixes_30 "Permanent link") * Move `getattr` warning in deprecated `BaseConfig` by [@tlambert03](https://github.com/tlambert03) in [#7183](https://github.com/pydantic/pydantic/pull/7183) * Only hash `model_fields`, not whole `__dict__` by [@alexmojaki](https://github.com/alexmojaki) in [#7786](https://github.com/pydantic/pydantic/pull/7786) * Fix mishandling of unions while freezing types in the `mypy` plugin by [@dmontagu](https://github.com/dmontagu) in [#7411](https://github.com/pydantic/pydantic/pull/7411) * Fix `mypy` error on untyped `ClassVar` by [@vincent-hachin-wmx](https://github.com/vincent-hachin-wmx) in [#8138](https://github.com/pydantic/pydantic/pull/8138) * Only compare pydantic fields in `BaseModel.__eq__` instead of whole `__dict__` by [@QuentinSoubeyranAqemia](https://github.com/QuentinSoubeyranAqemia) in [#7825](https://github.com/pydantic/pydantic/pull/7825) * Update `strict` docstring in `model_validate` method. by [@LukeTonin](https://github.com/LukeTonin) in [#8223](https://github.com/pydantic/pydantic/pull/8223) * Fix overload position of `computed_field` by [@Viicos](https://github.com/Viicos) in [#8227](https://github.com/pydantic/pydantic/pull/8227) * Fix custom type type casting used in multiple attributes by [@ianhfc](https://github.com/ianhfc) in [#8066](https://github.com/pydantic/pydantic/pull/8066) * Fix issue not allowing `validate_call` decorator to be dynamically assigned to a class method by [@jusexton](https://github.com/jusexton) in [#8249](https://github.com/pydantic/pydantic/pull/8249) * Fix issue `unittest.mock` deprecation warnings by [@ibleedicare](https://github.com/ibleedicare) in [#8262](https://github.com/pydantic/pydantic/pull/8262) * Added tests for the case `JsonValue` contains subclassed primitive values by [@jusexton](https://github.com/jusexton) in [#8286](https://github.com/pydantic/pydantic/pull/8286) * Fix `mypy` error on free before validator (classmethod) by [@sydney-runkle](https://github.com/sydney-runkle) in [#8285](https://github.com/pydantic/pydantic/pull/8285) * Fix `to_snake` conversion by [@jevins09](https://github.com/jevins09) in [#8316](https://github.com/pydantic/pydantic/pull/8316) * Fix type annotation of `ModelMetaclass.__prepare__` by [@slanzmich](https://github.com/slanzmich) in [#8305](https://github.com/pydantic/pydantic/pull/8305) * Disallow `config` specification when initializing a `TypeAdapter` when the annotated type has config already by [@sydney-runkle](https://github.com/sydney-runkle) in [#8365](https://github.com/pydantic/pydantic/pull/8365) * Fix a naming issue with JSON schema for generics parametrized by recursive type aliases by [@dmontagu](https://github.com/dmontagu) in [#8389](https://github.com/pydantic/pydantic/pull/8389) * Fix type annotation in pydantic people script by [@shenxiangzhuang](https://github.com/shenxiangzhuang) in [#8402](https://github.com/pydantic/pydantic/pull/8402) * Add support for field `alias` in `dataclass` signature by [@NeevCohen](https://github.com/NeevCohen) in [#8387](https://github.com/pydantic/pydantic/pull/8387) * Fix bug with schema generation with `Field(...)` in a forward ref by [@dmontagu](https://github.com/dmontagu) in [#8494](https://github.com/pydantic/pydantic/pull/8494) * Fix ordering of keys in `__dict__` with `model_construct` call by [@sydney-runkle](https://github.com/sydney-runkle) in [#8500](https://github.com/pydantic/pydantic/pull/8500) * Fix module `path_type` creation when globals does not contain `__name__` by [@hramezani](https://github.com/hramezani) in [#8470](https://github.com/pydantic/pydantic/pull/8470) * Fix for namespace issue with dataclasses with `from __future__ import annotations` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8513](https://github.com/pydantic/pydantic/pull/8513) * Fix: make function validator types positional-only by [@pmmmwh](https://github.com/pmmmwh) in [#8479](https://github.com/pydantic/pydantic/pull/8479) * Fix usage of `@deprecated` by [@Viicos](https://github.com/Viicos) in [#8294](https://github.com/pydantic/pydantic/pull/8294) * Add more support for private attributes in `model_construct` call by [@sydney-runkle](https://github.com/sydney-runkle) in [#8525](https://github.com/pydantic/pydantic/pull/8525) * Use a stack for the types namespace by [@dmontagu](https://github.com/dmontagu) in [#8378](https://github.com/pydantic/pydantic/pull/8378) * Fix schema-building bug with `TypeAliasType` for types with refs by [@dmontagu](https://github.com/dmontagu) in [#8526](https://github.com/pydantic/pydantic/pull/8526) * Support `pydantic.Field(repr=False)` in dataclasses by [@tigeryy2](https://github.com/tigeryy2) in [#8511](https://github.com/pydantic/pydantic/pull/8511) * Override `dataclass_transform` behavior for `RootModel` by [@Viicos](https://github.com/Viicos) in [#8163](https://github.com/pydantic/pydantic/pull/8163) * Refactor signature generation for simplicity by [@sydney-runkle](https://github.com/sydney-runkle) in [#8572](https://github.com/pydantic/pydantic/pull/8572) * Fix ordering bug of PlainValidator annotation by [@Anvil](https://github.com/Anvil) in [#8567](https://github.com/pydantic/pydantic/pull/8567) * Fix `exclude_none` for json serialization of `computed_field`s by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1098](https://github.com/pydantic/pydantic-core/pull/1098) * Support yyyy-MM-DD string for datetimes by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1124](https://github.com/pydantic/pydantic-core/pull/1124) * Tweak ordering of definitions in generated schemas by [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) in [#8583](https://github.com/pydantic/pydantic/pull/8583) ### New Contributors[¶](#new-contributors_12 "Permanent link") #### `pydantic`[¶](#pydantic_1 "Permanent link") * [@ekeew](https://github.com/ekeew) made their first contribution in [#6874](https://github.com/pydantic/pydantic/pull/6874) * [@lambertsbennett](https://github.com/lambertsbennett) made their first contribution in [#8054](https://github.com/pydantic/pydantic/pull/8054) * [@vincent-hachin-wmx](https://github.com/vincent-hachin-wmx) made their first contribution in [#8138](https://github.com/pydantic/pydantic/pull/8138) * [@QuentinSoubeyranAqemia](https://github.com/QuentinSoubeyranAqemia) made their first contribution in [#7825](https://github.com/pydantic/pydantic/pull/7825) * [@ariebovenberg](https://github.com/ariebovenberg) made their first contribution in [#8072](https://github.com/pydantic/pydantic/pull/8072) * [@LukeTonin](https://github.com/LukeTonin) made their first contribution in [#8223](https://github.com/pydantic/pydantic/pull/8223) * [@denisart](https://github.com/denisart) made their first contribution in [#8231](https://github.com/pydantic/pydantic/pull/8231) * [@ianhfc](https://github.com/ianhfc) made their first contribution in [#8066](https://github.com/pydantic/pydantic/pull/8066) * [@eonu](https://github.com/eonu) made their first contribution in [#8255](https://github.com/pydantic/pydantic/pull/8255) * [@amandahla](https://github.com/amandahla) made their first contribution in [#8263](https://github.com/pydantic/pydantic/pull/8263) * [@ibleedicare](https://github.com/ibleedicare) made their first contribution in [#8262](https://github.com/pydantic/pydantic/pull/8262) * [@jevins09](https://github.com/jevins09) made their first contribution in [#8316](https://github.com/pydantic/pydantic/pull/8316) * [@cuu508](https://github.com/cuu508) made their first contribution in [#8322](https://github.com/pydantic/pydantic/pull/8322) * [@slanzmich](https://github.com/slanzmich) made their first contribution in [#8305](https://github.com/pydantic/pydantic/pull/8305) * [@jensenbox](https://github.com/jensenbox) made their first contribution in [#8331](https://github.com/pydantic/pydantic/pull/8331) * [@szepeviktor](https://github.com/szepeviktor) made their first contribution in [#8356](https://github.com/pydantic/pydantic/pull/8356) * [@Elkiwa](https://github.com/Elkiwa) made their first contribution in [#8341](https://github.com/pydantic/pydantic/pull/8341) * [@parhamfh](https://github.com/parhamfh) made their first contribution in [#8395](https://github.com/pydantic/pydantic/pull/8395) * [@shenxiangzhuang](https://github.com/shenxiangzhuang) made their first contribution in [#8402](https://github.com/pydantic/pydantic/pull/8402) * [@NeevCohen](https://github.com/NeevCohen) made their first contribution in [#8387](https://github.com/pydantic/pydantic/pull/8387) * [@zby](https://github.com/zby) made their first contribution in [#8497](https://github.com/pydantic/pydantic/pull/8497) * [@patelnets](https://github.com/patelnets) made their first contribution in [#8491](https://github.com/pydantic/pydantic/pull/8491) * [@edwardwli](https://github.com/edwardwli) made their first contribution in [#8503](https://github.com/pydantic/pydantic/pull/8503) * [@luca-matei](https://github.com/luca-matei) made their first contribution in [#8507](https://github.com/pydantic/pydantic/pull/8507) * [@Jocelyn-Gas](https://github.com/Jocelyn-Gas) made their first contribution in [#8437](https://github.com/pydantic/pydantic/pull/8437) * [@bL34cHig0](https://github.com/bL34cHig0) made their first contribution in [#8501](https://github.com/pydantic/pydantic/pull/8501) * [@tigeryy2](https://github.com/tigeryy2) made their first contribution in [#8511](https://github.com/pydantic/pydantic/pull/8511) * [@geospackle](https://github.com/geospackle) made their first contribution in [#8537](https://github.com/pydantic/pydantic/pull/8537) * [@Anvil](https://github.com/Anvil) made their first contribution in [#8567](https://github.com/pydantic/pydantic/pull/8567) * [@hungtsetse](https://github.com/hungtsetse) made their first contribution in [#8546](https://github.com/pydantic/pydantic/pull/8546) * [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) made their first contribution in [#8583](https://github.com/pydantic/pydantic/pull/8583) #### `pydantic-core`[¶](#pydantic-core_1 "Permanent link") * [@mariuswinger](https://github.com/mariuswinger) made their first contribution in [pydantic/pydantic-core#1087](https://github.com/pydantic/pydantic-core/pull/1087) * [@adamchainz](https://github.com/adamchainz) made their first contribution in [pydantic/pydantic-core#1090](https://github.com/pydantic/pydantic-core/pull/1090) * [@akx](https://github.com/akx) made their first contribution in [pydantic/pydantic-core#1123](https://github.com/pydantic/pydantic-core/pull/1123) v2.6.0b1 (2024-01-19)[¶](#v260b1-2024-01-19 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.0b1) for details. v2.5.3 (2023-12-22)[¶](#v253-2023-12-22 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.3) ### What's Changed[¶](#whats-changed_31 "Permanent link") #### Packaging[¶](#packaging_21 "Permanent link") * uprev `pydantic-core` to 2.14.6 #### Fixes[¶](#fixes_31 "Permanent link") * Fix memory leak with recursive definitions creating reference cycles by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1125](https://github.com/pydantic/pydantic-core/pull/1125) v2.5.2 (2023-11-22)[¶](#v252-2023-11-22 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.2) ### What's Changed[¶](#whats-changed_32 "Permanent link") #### Packaging[¶](#packaging_22 "Permanent link") * uprev `pydantic-core` to 2.14.5 #### New Features[¶](#new-features_10 "Permanent link") * Add `ConfigDict.ser_json_inf_nan` by [@davidhewitt](https://github.com/davidhewitt) in [#8159](https://github.com/pydantic/pydantic/pull/8159) #### Fixes[¶](#fixes_32 "Permanent link") * Fix validation of `Literal` from JSON keys when used as `dict` key by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1075](https://github.com/pydantic/pydantic-core/pull/1075) * Fix bug re `custom_init` on members of `Union` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1076](https://github.com/pydantic/pydantic-core/pull/1076) * Fix `JsonValue` `bool` serialization by [@sydney-runkle](https://github.com/sydney-runkle) in [#8190](https://github.com/pydantic/pydantic/pull/8159) * Fix handling of unhashable inputs with `Literal` in `Union`s by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1089](https://github.com/pydantic/pydantic-core/pull/1089) v2.5.1 (2023-11-15)[¶](#v251-2023-11-15 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.1) ### What's Changed[¶](#whats-changed_33 "Permanent link") #### Packaging[¶](#packaging_23 "Permanent link") * uprev pydantic-core to 2.14.3 by [@samuelcolvin](https://github.com/samuelcolvin) in [#8120](https://github.com/pydantic/pydantic/pull/8120) #### Fixes[¶](#fixes_33 "Permanent link") * Fix package description limit by [@dmontagu](https://github.com/dmontagu) in [#8097](https://github.com/pydantic/pydantic/pull/8097) * Fix `ValidateCallWrapper` error when creating a model which has a [@validate\_call](https://github.com/validate_call) wrapped field annotation by [@sydney-runkle](https://github.com/sydney-runkle) in [#8110](https://github.com/pydantic/pydantic/pull/8110) v2.5.0 (2023-11-13)[¶](#v250-2023-11-13 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.0) The code released in v2.5.0 is functionally identical to that of v2.5.0b1. ### What's Changed[¶](#whats-changed_34 "Permanent link") #### Packaging[¶](#packaging_24 "Permanent link") * Update pydantic-core from 2.10.1 to 2.14.1, significant changes from these updates are described below, full changelog [here](https://github.com/pydantic/pydantic-core/compare/v2.10.1...v2.14.1) * Update to `pyright==1.1.335` by [@Viicos](https://github.com/Viicos) in [#8075](https://github.com/pydantic/pydantic/pull/8075) #### New Features[¶](#new-features_11 "Permanent link") * Allow plugins to catch non `ValidationError` errors by [@adriangb](https://github.com/adriangb) in [#7806](https://github.com/pydantic/pydantic/pull/7806) * Support `__doc__` argument in `create_model()` by [@chris-spann](https://github.com/chris-spann) in [#7863](https://github.com/pydantic/pydantic/pull/7863) * Expose `regex_engine` flag - meaning you can use with the Rust or Python regex libraries in constraints by [@utkini](https://github.com/utkini) in [#7768](https://github.com/pydantic/pydantic/pull/7768) * Save return type generated from type annotation in `ComputedFieldInfo` by [@alexmojaki](https://github.com/alexmojaki) in [#7889](https://github.com/pydantic/pydantic/pull/7889) * Adopting `ruff` formatter by [@Luca-Blight](https://github.com/Luca-Blight) in [#7930](https://github.com/pydantic/pydantic/pull/7930) * Added `validation_error_cause` to config by [@zakstucke](https://github.com/zakstucke) in [#7626](https://github.com/pydantic/pydantic/pull/7626) * Make path of the item to validate available in plugin by [@hramezani](https://github.com/hramezani) in [#7861](https://github.com/pydantic/pydantic/pull/7861) * Add `CallableDiscriminator` and `Tag` by [@dmontagu](https://github.com/dmontagu) in [#7983](https://github.com/pydantic/pydantic/pull/7983) * `CallableDiscriminator` renamed to `Discriminator` by [@dmontagu](https://github.com/dmontagu) in [#8047](https://github.com/pydantic/pydantic/pull/8047) * Make union case tags affect union error messages by [@dmontagu](https://github.com/dmontagu) in [#8001](https://github.com/pydantic/pydantic/pull/8001) * Add `examples` and `json_schema_extra` to `@computed_field` by [@alexmojaki](https://github.com/alexmojaki) in [#8013](https://github.com/pydantic/pydantic/pull/8013) * Add `JsonValue` type by [@dmontagu](https://github.com/dmontagu) in [#7998](https://github.com/pydantic/pydantic/pull/7998) * Allow `str` as argument to `Discriminator` by [@dmontagu](https://github.com/dmontagu) in [#8047](https://github.com/pydantic/pydantic/pull/8047) * Add `SchemaSerializer.__reduce__` method to enable pickle serialization by [@edoakes](https://github.com/edoakes) in [pydantic/pydantic-core#1006](https://github.com/pydantic/pydantic-core/pull/1006) #### Changes[¶](#changes_8 "Permanent link") * **Significant Change:** replace `ultra_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](https://github.com/davidhewitt) in [pydantic/pydantic-core#867](https://github.com/pydantic/pydantic-core/pull/867) * Add support for instance method reassignment when `extra='allow'` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7683](https://github.com/pydantic/pydantic/pull/7683) * Support JSON schema generation for `Enum` types with no cases by [@sydney-runkle](https://github.com/sydney-runkle) in [#7927](https://github.com/pydantic/pydantic/pull/7927) * Warn if a class inherits from `Generic` before `BaseModel` by [@alexmojaki](https://github.com/alexmojaki) in [#7891](https://github.com/pydantic/pydantic/pull/7891) #### Performance[¶](#performance_8 "Permanent link") * New custom JSON parser, `jiter` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#974](https://github.com/pydantic/pydantic-core/pull/974) * PGO build for MacOS M1 by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1063](https://github.com/pydantic/pydantic-core/pull/1063) * Use `__getattr__` for all package imports, improve import time by [@samuelcolvin](https://github.com/samuelcolvin) in [#7947](https://github.com/pydantic/pydantic/pull/7947) #### Fixes[¶](#fixes_34 "Permanent link") * Fix `mypy` issue with subclasses of `RootModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7677](https://github.com/pydantic/pydantic/pull/7677) * Properly rebuild the `FieldInfo` when a forward ref gets evaluated by [@dmontagu](https://github.com/dmontagu) in [#7698](https://github.com/pydantic/pydantic/pull/7698) * Fix failure to load `SecretStr` from JSON (regression in v2.4) by [@sydney-runkle](https://github.com/sydney-runkle) in [#7729](https://github.com/pydantic/pydantic/pull/7729) * Fix `defer_build` behavior with `TypeAdapter` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7736](https://github.com/pydantic/pydantic/pull/7736) * Improve compatibility with legacy `mypy` versions by [@dmontagu](https://github.com/dmontagu) in [#7742](https://github.com/pydantic/pydantic/pull/7742) * Fix: update `TypeVar` handling when default is not set by [@pmmmwh](https://github.com/pmmmwh) in [#7719](https://github.com/pydantic/pydantic/pull/7719) * Support specification of `strict` on `Enum` type fields by [@sydney-runkle](https://github.com/sydney-runkle) in [#7761](https://github.com/pydantic/pydantic/pull/7761) * Wrap `weakref.ref` instead of subclassing to fix `cloudpickle` serialization by [@edoakes](https://github.com/edoakes) in [#7780](https://github.com/pydantic/pydantic/pull/7780) * Keep values of private attributes set within `model_post_init` in subclasses by [@alexmojaki](https://github.com/alexmojaki) in [#7775](https://github.com/pydantic/pydantic/pull/7775) * Add more specific type for non-callable `json_schema_extra` by [@alexmojaki](https://github.com/alexmojaki) in [#7803](https://github.com/pydantic/pydantic/pull/7803) * Raise an error when deleting frozen (model) fields by [@alexmojaki](https://github.com/alexmojaki) in [#7800](https://github.com/pydantic/pydantic/pull/7800) * Fix schema sorting bug with default values by [@sydney-runkle](https://github.com/sydney-runkle) in [#7817](https://github.com/pydantic/pydantic/pull/7817) * Use generated alias for aliases that are not specified otherwise by [@alexmojaki](https://github.com/alexmojaki) in [#7802](https://github.com/pydantic/pydantic/pull/7802) * Support `strict` specification for `UUID` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#7865](https://github.com/pydantic/pydantic/pull/7865) * JSON schema: fix extra parameter handling by [@me-and](https://github.com/me-and) in [#7810](https://github.com/pydantic/pydantic/pull/7810) * Fix: support `pydantic.Field(kw_only=True)` with inherited dataclasses by [@PrettyWood](https://github.com/PrettyWood) in [#7827](https://github.com/pydantic/pydantic/pull/7827) * Support `validate_call` decorator for methods in classes with `__slots__` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7883](https://github.com/pydantic/pydantic/pull/7883) * Fix pydantic dataclass problem with `dataclasses.field` default by [@hramezani](https://github.com/hramezani) in [#7898](https://github.com/pydantic/pydantic/pull/7898) * Fix schema generation for generics with union type bounds by [@sydney-runkle](https://github.com/sydney-runkle) in [#7899](https://github.com/pydantic/pydantic/pull/7899) * Fix version for `importlib_metadata` on python 3.7 by [@sydney-runkle](https://github.com/sydney-runkle) in [#7904](https://github.com/pydantic/pydantic/pull/7904) * Support `|` operator (Union) in PydanticRecursiveRef by [@alexmojaki](https://github.com/alexmojaki) in [#7892](https://github.com/pydantic/pydantic/pull/7892) * Fix `display_as_type` for `TypeAliasType` in python 3.12 by [@dmontagu](https://github.com/dmontagu) in [#7929](https://github.com/pydantic/pydantic/pull/7929) * Add support for `NotRequired` generics in `TypedDict` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7932](https://github.com/pydantic/pydantic/pull/7932) * Make generic `TypeAliasType` specifications produce different schema definitions by [@alexdrydew](https://github.com/alexdrydew) in [#7893](https://github.com/pydantic/pydantic/pull/7893) * Added fix for signature of inherited dataclass by [@howsunjow](https://github.com/howsunjow) in [#7925](https://github.com/pydantic/pydantic/pull/7925) * Make the model name generation more robust in JSON schema by [@joakimnordling](https://github.com/joakimnordling) in [#7881](https://github.com/pydantic/pydantic/pull/7881) * Fix plurals in validation error messages (in tests) by [@Iipin](https://github.com/Iipin) in [#7972](https://github.com/pydantic/pydantic/pull/7972) * `PrivateAttr` is passed from `Annotated` default position by [@tabassco](https://github.com/tabassco) in [#8004](https://github.com/pydantic/pydantic/pull/8004) * Don't decode bytes (which may not be UTF8) when displaying SecretBytes by [@alexmojaki](https://github.com/alexmojaki) in [#8012](https://github.com/pydantic/pydantic/pull/8012) * Use `classmethod` instead of `classmethod[Any, Any, Any]` by [@Mr-Pepe](https://github.com/Mr-Pepe) in [#7979](https://github.com/pydantic/pydantic/pull/7979) * Clearer error on invalid Plugin by [@samuelcolvin](https://github.com/samuelcolvin) in [#8023](https://github.com/pydantic/pydantic/pull/8023) * Correct pydantic dataclasses import by [@samuelcolvin](https://github.com/samuelcolvin) in [#8027](https://github.com/pydantic/pydantic/pull/8027) * Fix misbehavior for models referencing redefined type aliases by [@dmontagu](https://github.com/dmontagu) in [#8050](https://github.com/pydantic/pydantic/pull/8050) * Fix `Optional` field with `validate_default` only performing one field validation by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1002](https://github.com/pydantic/pydantic-core/pull/1002) * Fix `definition-ref` bug with `Dict` keys by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1014](https://github.com/pydantic/pydantic-core/pull/1014) * Fix bug allowing validation of `bool` types with `coerce_numbers_to_str=True` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1017](https://github.com/pydantic/pydantic-core/pull/1017) * Don't accept `NaN` in float and decimal constraints by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1037](https://github.com/pydantic/pydantic-core/pull/1037) * Add `lax_str` and `lax_int` support for enum values not inherited from str/int by [@michaelhly](https://github.com/michaelhly) in [pydantic/pydantic-core#1015](https://github.com/pydantic/pydantic-core/pull/1015) * Support subclasses in lists in `Union` of `List` types by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1039](https://github.com/pydantic/pydantic-core/pull/1039) * Allow validation against `max_digits` and `decimals` to pass if normalized or non-normalized input is valid by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1049](https://github.com/pydantic/pydantic-core/pull/1049) * Fix: proper pluralization in `ValidationError` messages by [@Iipin](https://github.com/Iipin) in [pydantic/pydantic-core#1050](https://github.com/pydantic/pydantic-core/pull/1050) * Disallow the string `'-'` as `datetime` input by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/speedate#52](https://github.com/pydantic/speedate/pull/52) & [pydantic/pydantic-core#1060](https://github.com/pydantic/pydantic-core/pull/1060) * Fix: NaN and Inf float serialization by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1062](https://github.com/pydantic/pydantic-core/pull/1062) * Restore manylinux-compatible PGO builds by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1068](https://github.com/pydantic/pydantic-core/pull/1068) ### New Contributors[¶](#new-contributors_13 "Permanent link") #### `pydantic`[¶](#pydantic_2 "Permanent link") * [@schneebuzz](https://github.com/schneebuzz) made their first contribution in [#7699](https://github.com/pydantic/pydantic/pull/7699) * [@edoakes](https://github.com/edoakes) made their first contribution in [#7780](https://github.com/pydantic/pydantic/pull/7780) * [@alexmojaki](https://github.com/alexmojaki) made their first contribution in [#7775](https://github.com/pydantic/pydantic/pull/7775) * [@NickG123](https://github.com/NickG123) made their first contribution in [#7751](https://github.com/pydantic/pydantic/pull/7751) * [@gowthamgts](https://github.com/gowthamgts) made their first contribution in [#7830](https://github.com/pydantic/pydantic/pull/7830) * [@jamesbraza](https://github.com/jamesbraza) made their first contribution in [#7848](https://github.com/pydantic/pydantic/pull/7848) * [@laundmo](https://github.com/laundmo) made their first contribution in [#7850](https://github.com/pydantic/pydantic/pull/7850) * [@rahmatnazali](https://github.com/rahmatnazali) made their first contribution in [#7870](https://github.com/pydantic/pydantic/pull/7870) * [@waterfountain1996](https://github.com/waterfountain1996) made their first contribution in [#7878](https://github.com/pydantic/pydantic/pull/7878) * [@chris-spann](https://github.com/chris-spann) made their first contribution in [#7863](https://github.com/pydantic/pydantic/pull/7863) * [@me-and](https://github.com/me-and) made their first contribution in [#7810](https://github.com/pydantic/pydantic/pull/7810) * [@utkini](https://github.com/utkini) made their first contribution in [#7768](https://github.com/pydantic/pydantic/pull/7768) * [@bn-l](https://github.com/bn-l) made their first contribution in [#7744](https://github.com/pydantic/pydantic/pull/7744) * [@alexdrydew](https://github.com/alexdrydew) made their first contribution in [#7893](https://github.com/pydantic/pydantic/pull/7893) * [@Luca-Blight](https://github.com/Luca-Blight) made their first contribution in [#7930](https://github.com/pydantic/pydantic/pull/7930) * [@howsunjow](https://github.com/howsunjow) made their first contribution in [#7925](https://github.com/pydantic/pydantic/pull/7925) * [@joakimnordling](https://github.com/joakimnordling) made their first contribution in [#7881](https://github.com/pydantic/pydantic/pull/7881) * [@icfly2](https://github.com/icfly2) made their first contribution in [#7976](https://github.com/pydantic/pydantic/pull/7976) * [@Yummy-Yums](https://github.com/Yummy-Yums) made their first contribution in [#8003](https://github.com/pydantic/pydantic/pull/8003) * [@Iipin](https://github.com/Iipin) made their first contribution in [#7972](https://github.com/pydantic/pydantic/pull/7972) * [@tabassco](https://github.com/tabassco) made their first contribution in [#8004](https://github.com/pydantic/pydantic/pull/8004) * [@Mr-Pepe](https://github.com/Mr-Pepe) made their first contribution in [#7979](https://github.com/pydantic/pydantic/pull/7979) * [@0x00cl](https://github.com/0x00cl) made their first contribution in [#8010](https://github.com/pydantic/pydantic/pull/8010) * [@barraponto](https://github.com/barraponto) made their first contribution in [#8032](https://github.com/pydantic/pydantic/pull/8032) #### `pydantic-core`[¶](#pydantic-core_2 "Permanent link") * [@sisp](https://github.com/sisp) made their first contribution in [pydantic/pydantic-core#995](https://github.com/pydantic/pydantic-core/pull/995) * [@michaelhly](https://github.com/michaelhly) made their first contribution in [pydantic/pydantic-core#1015](https://github.com/pydantic/pydantic-core/pull/1015) v2.5.0b1 (2023-11-09)[¶](#v250b1-2023-11-09 "Permanent link") -------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.0b1) for details. v2.4.2 (2023-09-27)[¶](#v242-2023-09-27 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.2) ### What's Changed[¶](#whats-changed_35 "Permanent link") #### Fixes[¶](#fixes_35 "Permanent link") * Fix bug with JSON schema for sequence of discriminated union by [@dmontagu](https://github.com/dmontagu) in [#7647](https://github.com/pydantic/pydantic/pull/7647) * Fix schema references in discriminated unions by [@adriangb](https://github.com/adriangb) in [#7646](https://github.com/pydantic/pydantic/pull/7646) * Fix json schema generation for recursive models by [@adriangb](https://github.com/adriangb) in [#7653](https://github.com/pydantic/pydantic/pull/7653) * Fix `models_json_schema` for generic models by [@adriangb](https://github.com/adriangb) in [#7654](https://github.com/pydantic/pydantic/pull/7654) * Fix xfailed test for generic model signatures by [@adriangb](https://github.com/adriangb) in [#7658](https://github.com/pydantic/pydantic/pull/7658) ### New Contributors[¶](#new-contributors_14 "Permanent link") * [@austinorr](https://github.com/austinorr) made their first contribution in [#7657](https://github.com/pydantic/pydantic/pull/7657) * [@peterHoburg](https://github.com/peterHoburg) made their first contribution in [#7670](https://github.com/pydantic/pydantic/pull/7670) v2.4.1 (2023-09-26)[¶](#v241-2023-09-26 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.1) ### What's Changed[¶](#whats-changed_36 "Permanent link") #### Packaging[¶](#packaging_25 "Permanent link") * Update pydantic-core to 2.10.1 by [@davidhewitt](https://github.com/davidhewitt) in [#7633](https://github.com/pydantic/pydantic/pull/7633) #### Fixes[¶](#fixes_36 "Permanent link") * Serialize unsubstituted type vars as `Any` by [@adriangb](https://github.com/adriangb) in [#7606](https://github.com/pydantic/pydantic/pull/7606) * Remove schema building caches by [@adriangb](https://github.com/adriangb) in [#7624](https://github.com/pydantic/pydantic/pull/7624) * Fix an issue where JSON schema extras weren't JSON encoded by [@dmontagu](https://github.com/dmontagu) in [#7625](https://github.com/pydantic/pydantic/pull/7625) v2.4.0 (2023-09-22)[¶](#v240-2023-09-22 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.0) ### What's Changed[¶](#whats-changed_37 "Permanent link") #### Packaging[¶](#packaging_26 "Permanent link") * Update pydantic-core to 2.10.0 by [@samuelcolvin](https://github.com/samuelcolvin) in [#7542](https://github.com/pydantic/pydantic/pull/7542) #### New Features[¶](#new-features_12 "Permanent link") * Add `Base64Url` types by [@dmontagu](https://github.com/dmontagu) in [#7286](https://github.com/pydantic/pydantic/pull/7286) * Implement optional `number` to `str` coercion by [@lig](https://github.com/lig) in [#7508](https://github.com/pydantic/pydantic/pull/7508) * Allow access to `field_name` and `data` in all validators if there is data and a field name by [@samuelcolvin](https://github.com/samuelcolvin) in [#7542](https://github.com/pydantic/pydantic/pull/7542) * Add `BaseModel.model_validate_strings` and `TypeAdapter.validate_strings` by [@hramezani](https://github.com/hramezani) in [#7552](https://github.com/pydantic/pydantic/pull/7552) * Add Pydantic `plugins` experimental implementation by [@lig](https://github.com/lig) [@samuelcolvin](https://github.com/samuelcolvin) and [@Kludex](https://github.com/Kludex) in [#6820](https://github.com/pydantic/pydantic/pull/6820) #### Changes[¶](#changes_9 "Permanent link") * Do not override `model_post_init` in subclass with private attrs by [@Viicos](https://github.com/Viicos) in [#7302](https://github.com/pydantic/pydantic/pull/7302) * Make fields with defaults not required in the serialization schema by default by [@dmontagu](https://github.com/dmontagu) in [#7275](https://github.com/pydantic/pydantic/pull/7275) * Mark `Extra` as deprecated by [@disrupted](https://github.com/disrupted) in [#7299](https://github.com/pydantic/pydantic/pull/7299) * Make `EncodedStr` a dataclass by [@Kludex](https://github.com/Kludex) in [#7396](https://github.com/pydantic/pydantic/pull/7396) * Move `annotated_handlers` to be public by [@samuelcolvin](https://github.com/samuelcolvin) in [#7569](https://github.com/pydantic/pydantic/pull/7569) #### Performance[¶](#performance_9 "Permanent link") * Simplify flattening and inlining of `CoreSchema` by [@adriangb](https://github.com/adriangb) in [#7523](https://github.com/pydantic/pydantic/pull/7523) * Remove unused copies in `CoreSchema` walking by [@adriangb](https://github.com/adriangb) in [#7528](https://github.com/pydantic/pydantic/pull/7528) * Add caches for collecting definitions and invalid schemas from a CoreSchema by [@adriangb](https://github.com/adriangb) in [#7527](https://github.com/pydantic/pydantic/pull/7527) * Eagerly resolve discriminated unions and cache cases where we can't by [@adriangb](https://github.com/adriangb) in [#7529](https://github.com/pydantic/pydantic/pull/7529) * Replace `dict.get` and `dict.setdefault` with more verbose versions in `CoreSchema` building hot paths by [@adriangb](https://github.com/adriangb) in [#7536](https://github.com/pydantic/pydantic/pull/7536) * Cache invalid `CoreSchema` discovery by [@adriangb](https://github.com/adriangb) in [#7535](https://github.com/pydantic/pydantic/pull/7535) * Allow disabling `CoreSchema` validation for faster startup times by [@adriangb](https://github.com/adriangb) in [#7565](https://github.com/pydantic/pydantic/pull/7565) #### Fixes[¶](#fixes_37 "Permanent link") * Fix config detection for `TypedDict` from grandparent classes by [@dmontagu](https://github.com/dmontagu) in [#7272](https://github.com/pydantic/pydantic/pull/7272) * Fix hash function generation for frozen models with unusual MRO by [@dmontagu](https://github.com/dmontagu) in [#7274](https://github.com/pydantic/pydantic/pull/7274) * Make `strict` config overridable in field for Path by [@hramezani](https://github.com/hramezani) in [#7281](https://github.com/pydantic/pydantic/pull/7281) * Use `ser_json_` on default in `GenerateJsonSchema` by [@Kludex](https://github.com/Kludex) in [#7269](https://github.com/pydantic/pydantic/pull/7269) * Adding a check that alias is validated as an identifier for Python by [@andree0](https://github.com/andree0) in [#7319](https://github.com/pydantic/pydantic/pull/7319) * Raise an error when computed field overrides field by [@sydney-runkle](https://github.com/sydney-runkle) in [#7346](https://github.com/pydantic/pydantic/pull/7346) * Fix applying `SkipValidation` to referenced schemas by [@adriangb](https://github.com/adriangb) in [#7381](https://github.com/pydantic/pydantic/pull/7381) * Enforce behavior of private attributes having double leading underscore by [@lig](https://github.com/lig) in [#7265](https://github.com/pydantic/pydantic/pull/7265) * Standardize `__get_pydantic_core_schema__` signature by [@hramezani](https://github.com/hramezani) in [#7415](https://github.com/pydantic/pydantic/pull/7415) * Fix generic dataclass fields mutation bug (when using `TypeAdapter`) by [@sydney-runkle](https://github.com/sydney-runkle) in [#7435](https://github.com/pydantic/pydantic/pull/7435) * Fix `TypeError` on `model_validator` in `wrap` mode by [@pmmmwh](https://github.com/pmmmwh) in [#7496](https://github.com/pydantic/pydantic/pull/7496) * Improve enum error message by [@hramezani](https://github.com/hramezani) in [#7506](https://github.com/pydantic/pydantic/pull/7506) * Make `repr` work for instances that failed initialization when handling `ValidationError`s by [@dmontagu](https://github.com/dmontagu) in [#7439](https://github.com/pydantic/pydantic/pull/7439) * Fixed a regular expression denial of service issue by limiting whitespaces by [@prodigysml](https://github.com/prodigysml) in [#7360](https://github.com/pydantic/pydantic/pull/7360) * Fix handling of `UUID` values having `UUID.version=None` by [@lig](https://github.com/lig) in [#7566](https://github.com/pydantic/pydantic/pull/7566) * Fix `__iter__` returning private `cached_property` info by [@sydney-runkle](https://github.com/sydney-runkle) in [#7570](https://github.com/pydantic/pydantic/pull/7570) * Improvements to version info message by [@samuelcolvin](https://github.com/samuelcolvin) in [#7594](https://github.com/pydantic/pydantic/pull/7594) ### New Contributors[¶](#new-contributors_15 "Permanent link") * [@15498th](https://github.com/15498th) made their first contribution in [#7238](https://github.com/pydantic/pydantic/pull/7238) * [@GabrielCappelli](https://github.com/GabrielCappelli) made their first contribution in [#7213](https://github.com/pydantic/pydantic/pull/7213) * [@tobni](https://github.com/tobni) made their first contribution in [#7184](https://github.com/pydantic/pydantic/pull/7184) * [@redruin1](https://github.com/redruin1) made their first contribution in [#7282](https://github.com/pydantic/pydantic/pull/7282) * [@FacerAin](https://github.com/FacerAin) made their first contribution in [#7288](https://github.com/pydantic/pydantic/pull/7288) * [@acdha](https://github.com/acdha) made their first contribution in [#7297](https://github.com/pydantic/pydantic/pull/7297) * [@andree0](https://github.com/andree0) made their first contribution in [#7319](https://github.com/pydantic/pydantic/pull/7319) * [@gordonhart](https://github.com/gordonhart) made their first contribution in [#7375](https://github.com/pydantic/pydantic/pull/7375) * [@pmmmwh](https://github.com/pmmmwh) made their first contribution in [#7496](https://github.com/pydantic/pydantic/pull/7496) * [@disrupted](https://github.com/disrupted) made their first contribution in [#7299](https://github.com/pydantic/pydantic/pull/7299) * [@prodigysml](https://github.com/prodigysml) made their first contribution in [#7360](https://github.com/pydantic/pydantic/pull/7360) v2.3.0 (2023-08-23)[¶](#v230-2023-08-23 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.3.0) * 🔥 Remove orphaned changes file from repo by [@lig](https://github.com/lig) in [#7168](https://github.com/pydantic/pydantic/pull/7168) * Add copy button on documentation by [@Kludex](https://github.com/Kludex) in [#7190](https://github.com/pydantic/pydantic/pull/7190) * Fix docs on JSON type by [@Kludex](https://github.com/Kludex) in [#7189](https://github.com/pydantic/pydantic/pull/7189) * Update mypy 1.5.0 to 1.5.1 in CI by [@hramezani](https://github.com/hramezani) in [#7191](https://github.com/pydantic/pydantic/pull/7191) * fix download links badge by [@samuelcolvin](https://github.com/samuelcolvin) in [#7200](https://github.com/pydantic/pydantic/pull/7200) * add 2.2.1 to changelog by [@samuelcolvin](https://github.com/samuelcolvin) in [#7212](https://github.com/pydantic/pydantic/pull/7212) * Make ModelWrapValidator protocols generic by [@dmontagu](https://github.com/dmontagu) in [#7154](https://github.com/pydantic/pydantic/pull/7154) * Correct `Field(..., exclude: bool)` docs by [@samuelcolvin](https://github.com/samuelcolvin) in [#7214](https://github.com/pydantic/pydantic/pull/7214) * Make shadowing attributes a warning instead of an error by [@adriangb](https://github.com/adriangb) in [#7193](https://github.com/pydantic/pydantic/pull/7193) * Document `Base64Str` and `Base64Bytes` by [@Kludex](https://github.com/Kludex) in [#7192](https://github.com/pydantic/pydantic/pull/7192) * Fix `config.defer_build` for serialization first cases by [@samuelcolvin](https://github.com/samuelcolvin) in [#7024](https://github.com/pydantic/pydantic/pull/7024) * clean Model docstrings in JSON Schema by [@samuelcolvin](https://github.com/samuelcolvin) in [#7210](https://github.com/pydantic/pydantic/pull/7210) * fix [#7228](https://github.com/pydantic/pydantic/pull/7228) (typo): docs in `validators.md` to correct `validate_default` kwarg by [@lmmx](https://github.com/lmmx) in [#7229](https://github.com/pydantic/pydantic/pull/7229) * ✅ Implement `tzinfo.fromutc` method for `TzInfo` in `pydantic-core` by [@lig](https://github.com/lig) in [#7019](https://github.com/pydantic/pydantic/pull/7019) * Support `__get_validators__` by [@hramezani](https://github.com/hramezani) in [#7197](https://github.com/pydantic/pydantic/pull/7197) v2.2.1 (2023-08-18)[¶](#v221-2023-08-18 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.2.1) * Make `xfail`ing test for root model extra stop `xfail`ing by [@dmontagu](https://github.com/dmontagu) in [#6937](https://github.com/pydantic/pydantic/pull/6937) * Optimize recursion detection by stopping on the second visit for the same object by [@mciucu](https://github.com/mciucu) in [#7160](https://github.com/pydantic/pydantic/pull/7160) * fix link in docs by [@tlambert03](https://github.com/tlambert03) in [#7166](https://github.com/pydantic/pydantic/pull/7166) * Replace MiMalloc w/ default allocator by [@adriangb](https://github.com/adriangb) in [pydantic/pydantic-core#900](https://github.com/pydantic/pydantic-core/pull/900) * Bump pydantic-core to 2.6.1 and prepare 2.2.1 release by [@adriangb](https://github.com/adriangb) in [#7176](https://github.com/pydantic/pydantic/pull/7176) v2.2.0 (2023-08-17)[¶](#v220-2023-08-17 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.2.0) * Split "pipx install" setup command into two commands on the documentation site by [@nomadmtb](https://github.com/nomadmtb) in [#6869](https://github.com/pydantic/pydantic/pull/6869) * Deprecate `Field.include` by [@hramezani](https://github.com/hramezani) in [#6852](https://github.com/pydantic/pydantic/pull/6852) * Fix typo in default factory error msg by [@hramezani](https://github.com/hramezani) in [#6880](https://github.com/pydantic/pydantic/pull/6880) * Simplify handling of typing.Annotated in GenerateSchema by [@dmontagu](https://github.com/dmontagu) in [#6887](https://github.com/pydantic/pydantic/pull/6887) * Re-enable fastapi tests in CI by [@dmontagu](https://github.com/dmontagu) in [#6883](https://github.com/pydantic/pydantic/pull/6883) * Make it harder to hit collisions with json schema defrefs by [@dmontagu](https://github.com/dmontagu) in [#6566](https://github.com/pydantic/pydantic/pull/6566) * Cleaner error for invalid input to `Path` fields by [@samuelcolvin](https://github.com/samuelcolvin) in [#6903](https://github.com/pydantic/pydantic/pull/6903) * ![📝](https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/svg/1f4dd.svg ":memo:") support Coordinate Type by [@yezz123](https://github.com/yezz123) in [#6906](https://github.com/pydantic/pydantic/pull/6906) * Fix `ForwardRef` wrapper for py 3.10.0 (shim until bpo-45166) by [@randomir](https://github.com/randomir) in [#6919](https://github.com/pydantic/pydantic/pull/6919) * Fix misbehavior related to copying of RootModel by [@dmontagu](https://github.com/dmontagu) in [#6918](https://github.com/pydantic/pydantic/pull/6918) * Fix issue with recursion error caused by ParamSpec by [@dmontagu](https://github.com/dmontagu) in [#6923](https://github.com/pydantic/pydantic/pull/6923) * Add section about Constrained classes to the Migration Guide by [@Kludex](https://github.com/Kludex) in [#6924](https://github.com/pydantic/pydantic/pull/6924) * Use `main` branch for badge links by [@Viicos](https://github.com/Viicos) in [#6925](https://github.com/pydantic/pydantic/pull/6925) * Add test for v1/v2 Annotated discrepancy by [@carlbordum](https://github.com/carlbordum) in [#6926](https://github.com/pydantic/pydantic/pull/6926) * Make the v1 mypy plugin work with both v1 and v2 by [@dmontagu](https://github.com/dmontagu) in [#6921](https://github.com/pydantic/pydantic/pull/6921) * Fix issue where generic models couldn't be parametrized with BaseModel by [@dmontagu](https://github.com/dmontagu) in [#6933](https://github.com/pydantic/pydantic/pull/6933) * Remove xfail for discriminated union with alias by [@dmontagu](https://github.com/dmontagu) in [#6938](https://github.com/pydantic/pydantic/pull/6938) * add field\_serializer to computed\_field by [@andresliszt](https://github.com/andresliszt) in [#6965](https://github.com/pydantic/pydantic/pull/6965) * Use union\_schema with Type\[Union\[...\]\] by [@JeanArhancet](https://github.com/JeanArhancet) in [#6952](https://github.com/pydantic/pydantic/pull/6952) * Fix inherited typeddict attributes / config by [@adriangb](https://github.com/adriangb) in [#6981](https://github.com/pydantic/pydantic/pull/6981) * fix dataclass annotated before validator called twice by [@davidhewitt](https://github.com/davidhewitt) in [#6998](https://github.com/pydantic/pydantic/pull/6998) * Update test-fastapi deselected tests by [@hramezani](https://github.com/hramezani) in [#7014](https://github.com/pydantic/pydantic/pull/7014) * Fix validator doc format by [@hramezani](https://github.com/hramezani) in [#7015](https://github.com/pydantic/pydantic/pull/7015) * Fix typo in docstring of model\_json\_schema by [@AdamVinch-Federated](https://github.com/AdamVinch-Federated) in [#7032](https://github.com/pydantic/pydantic/pull/7032) * remove unused "type ignores" with pyright by [@samuelcolvin](https://github.com/samuelcolvin) in [#7026](https://github.com/pydantic/pydantic/pull/7026) * Add benchmark representing FastAPI startup time by [@adriangb](https://github.com/adriangb) in [#7030](https://github.com/pydantic/pydantic/pull/7030) * Fix json\_encoders for Enum subclasses by [@adriangb](https://github.com/adriangb) in [#7029](https://github.com/pydantic/pydantic/pull/7029) * Update docstring of `ser_json_bytes` regarding base64 encoding by [@Viicos](https://github.com/Viicos) in [#7052](https://github.com/pydantic/pydantic/pull/7052) * Allow `@validate_call` to work on async methods by [@adriangb](https://github.com/adriangb) in [#7046](https://github.com/pydantic/pydantic/pull/7046) * Fix: mypy error with `Settings` and `SettingsConfigDict` by [@JeanArhancet](https://github.com/JeanArhancet) in [#7002](https://github.com/pydantic/pydantic/pull/7002) * Fix some typos (repeated words and it's/its) by [@eumiro](https://github.com/eumiro) in [#7063](https://github.com/pydantic/pydantic/pull/7063) * Fix the typo in docstring by [@harunyasar](https://github.com/harunyasar) in [#7062](https://github.com/pydantic/pydantic/pull/7062) * Docs: Fix broken URL in the pydantic-settings package recommendation by [@swetjen](https://github.com/swetjen) in [#6995](https://github.com/pydantic/pydantic/pull/6995) * Handle constraints being applied to schemas that don't accept it by [@adriangb](https://github.com/adriangb) in [#6951](https://github.com/pydantic/pydantic/pull/6951) * Replace almost\_equal\_floats with math.isclose by [@eumiro](https://github.com/eumiro) in [#7082](https://github.com/pydantic/pydantic/pull/7082) * bump pydantic-core to 2.5.0 by [@davidhewitt](https://github.com/davidhewitt) in [#7077](https://github.com/pydantic/pydantic/pull/7077) * Add `short_version` and use it in links by [@hramezani](https://github.com/hramezani) in [#7115](https://github.com/pydantic/pydantic/pull/7115) * 📝 Add usage link to `RootModel` by [@Kludex](https://github.com/Kludex) in [#7113](https://github.com/pydantic/pydantic/pull/7113) * Revert "Fix default port for mongosrv DSNs (#6827)" by [@Kludex](https://github.com/Kludex) in [#7116](https://github.com/pydantic/pydantic/pull/7116) * Clarify validate\_default and \_Unset handling in usage docs and migration guide by [@benbenbang](https://github.com/benbenbang) in [#6950](https://github.com/pydantic/pydantic/pull/6950) * Tweak documentation of `Field.exclude` by [@Viicos](https://github.com/Viicos) in [#7086](https://github.com/pydantic/pydantic/pull/7086) * Do not require `validate_assignment` to use `Field.frozen` by [@Viicos](https://github.com/Viicos) in [#7103](https://github.com/pydantic/pydantic/pull/7103) * tweaks to `_core_utils` by [@samuelcolvin](https://github.com/samuelcolvin) in [#7040](https://github.com/pydantic/pydantic/pull/7040) * Make DefaultDict working with set by [@hramezani](https://github.com/hramezani) in [#7126](https://github.com/pydantic/pydantic/pull/7126) * Don't always require typing.Generic as a base for partially parametrized models by [@dmontagu](https://github.com/dmontagu) in [#7119](https://github.com/pydantic/pydantic/pull/7119) * Fix issue with JSON schema incorrectly using parent class core schema by [@dmontagu](https://github.com/dmontagu) in [#7020](https://github.com/pydantic/pydantic/pull/7020) * Fix xfailed test related to TypedDict and alias\_generator by [@dmontagu](https://github.com/dmontagu) in [#6940](https://github.com/pydantic/pydantic/pull/6940) * Improve error message for NameEmail by [@dmontagu](https://github.com/dmontagu) in [#6939](https://github.com/pydantic/pydantic/pull/6939) * Fix generic computed fields by [@dmontagu](https://github.com/dmontagu) in [#6988](https://github.com/pydantic/pydantic/pull/6988) * Reflect namedtuple default values during validation by [@dmontagu](https://github.com/dmontagu) in [#7144](https://github.com/pydantic/pydantic/pull/7144) * Update dependencies, fix pydantic-core usage, fix CI issues by [@dmontagu](https://github.com/dmontagu) in [#7150](https://github.com/pydantic/pydantic/pull/7150) * Add mypy 1.5.0 by [@hramezani](https://github.com/hramezani) in [#7118](https://github.com/pydantic/pydantic/pull/7118) * Handle non-json native enum values by [@adriangb](https://github.com/adriangb) in [#7056](https://github.com/pydantic/pydantic/pull/7056) * document `round_trip` in Json type documentation by [@jc-louis](https://github.com/jc-louis) in [#7137](https://github.com/pydantic/pydantic/pull/7137) * Relax signature checks to better support builtins and C extension functions as validators by [@adriangb](https://github.com/adriangb) in [#7101](https://github.com/pydantic/pydantic/pull/7101) * add union\_mode='left\_to\_right' by [@davidhewitt](https://github.com/davidhewitt) in [#7151](https://github.com/pydantic/pydantic/pull/7151) * Include an error message hint for inherited ordering by [@yvalencia91](https://github.com/yvalencia91) in [#7124](https://github.com/pydantic/pydantic/pull/7124) * Fix one docs link and resolve some warnings for two others by [@dmontagu](https://github.com/dmontagu) in [#7153](https://github.com/pydantic/pydantic/pull/7153) * Include Field extra keys name in warning by [@hramezani](https://github.com/hramezani) in [#7136](https://github.com/pydantic/pydantic/pull/7136) v2.1.1 (2023-07-25)[¶](#v211-2023-07-25 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.1.1) * Skip FieldInfo merging when unnecessary by [@dmontagu](https://github.com/dmontagu) in [#6862](https://github.com/pydantic/pydantic/pull/6862) v2.1.0 (2023-07-25)[¶](#v210-2023-07-25 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.1.0) * Add `StringConstraints` for use as Annotated metadata by [@adriangb](https://github.com/adriangb) in [#6605](https://github.com/pydantic/pydantic/pull/6605) * Try to fix intermittently failing CI by [@adriangb](https://github.com/adriangb) in [#6683](https://github.com/pydantic/pydantic/pull/6683) * Remove redundant example of optional vs default. by [@ehiggs-deliverect](https://github.com/ehiggs-deliverect) in [#6676](https://github.com/pydantic/pydantic/pull/6676) * Docs update by [@samuelcolvin](https://github.com/samuelcolvin) in [#6692](https://github.com/pydantic/pydantic/pull/6692) * Remove the Validate always section in validator docs by [@adriangb](https://github.com/adriangb) in [#6679](https://github.com/pydantic/pydantic/pull/6679) * Fix recursion error in json schema generation by [@adriangb](https://github.com/adriangb) in [#6720](https://github.com/pydantic/pydantic/pull/6720) * Fix incorrect subclass check for secretstr by [@AlexVndnblcke](https://github.com/AlexVndnblcke) in [#6730](https://github.com/pydantic/pydantic/pull/6730) * update pdm / pdm lockfile to 2.8.0 by [@davidhewitt](https://github.com/davidhewitt) in [#6714](https://github.com/pydantic/pydantic/pull/6714) * unpin pdm on more CI jobs by [@davidhewitt](https://github.com/davidhewitt) in [#6755](https://github.com/pydantic/pydantic/pull/6755) * improve source locations for auxiliary packages in docs by [@davidhewitt](https://github.com/davidhewitt) in [#6749](https://github.com/pydantic/pydantic/pull/6749) * Assume builtins don't accept an info argument by [@adriangb](https://github.com/adriangb) in [#6754](https://github.com/pydantic/pydantic/pull/6754) * Fix bug where calling `help(BaseModelSubclass)` raises errors by [@hramezani](https://github.com/hramezani) in [#6758](https://github.com/pydantic/pydantic/pull/6758) * Fix mypy plugin handling of `@model_validator(mode="after")` by [@ljodal](https://github.com/ljodal) in [#6753](https://github.com/pydantic/pydantic/pull/6753) * update pydantic-core to 2.3.1 by [@davidhewitt](https://github.com/davidhewitt) in [#6756](https://github.com/pydantic/pydantic/pull/6756) * Mypy plugin for settings by [@hramezani](https://github.com/hramezani) in [#6760](https://github.com/pydantic/pydantic/pull/6760) * Use `contentSchema` keyword for JSON schema by [@dmontagu](https://github.com/dmontagu) in [#6715](https://github.com/pydantic/pydantic/pull/6715) * fast-path checking finite decimals by [@davidhewitt](https://github.com/davidhewitt) in [#6769](https://github.com/pydantic/pydantic/pull/6769) * Docs update by [@samuelcolvin](https://github.com/samuelcolvin) in [#6771](https://github.com/pydantic/pydantic/pull/6771) * Improve json schema doc by [@hramezani](https://github.com/hramezani) in [#6772](https://github.com/pydantic/pydantic/pull/6772) * Update validator docs by [@adriangb](https://github.com/adriangb) in [#6695](https://github.com/pydantic/pydantic/pull/6695) * Fix typehint for wrap validator by [@dmontagu](https://github.com/dmontagu) in [#6788](https://github.com/pydantic/pydantic/pull/6788) * 🐛 Fix validation warning for unions of Literal and other type by [@lig](https://github.com/lig) in [#6628](https://github.com/pydantic/pydantic/pull/6628) * Update documentation for generics support in V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6685](https://github.com/pydantic/pydantic/pull/6685) * add pydantic-core build info to `version_info()` by [@samuelcolvin](https://github.com/samuelcolvin) in [#6785](https://github.com/pydantic/pydantic/pull/6785) * Fix pydantic dataclasses that use slots with default values by [@dmontagu](https://github.com/dmontagu) in [#6796](https://github.com/pydantic/pydantic/pull/6796) * Fix inheritance of hash function for frozen models by [@dmontagu](https://github.com/dmontagu) in [#6789](https://github.com/pydantic/pydantic/pull/6789) * ✨ Add `SkipJsonSchema` annotation by [@Kludex](https://github.com/Kludex) in [#6653](https://github.com/pydantic/pydantic/pull/6653) * Error if an invalid field name is used with Field by [@dmontagu](https://github.com/dmontagu) in [#6797](https://github.com/pydantic/pydantic/pull/6797) * Add `GenericModel` to `MOVED_IN_V2` by [@adriangb](https://github.com/adriangb) in [#6776](https://github.com/pydantic/pydantic/pull/6776) * Remove unused code from `docs/usage/types/custom.md` by [@hramezani](https://github.com/hramezani) in [#6803](https://github.com/pydantic/pydantic/pull/6803) * Fix `float` -> `Decimal` coercion precision loss by [@adriangb](https://github.com/adriangb) in [#6810](https://github.com/pydantic/pydantic/pull/6810) * remove email validation from the north star benchmark by [@davidhewitt](https://github.com/davidhewitt) in [#6816](https://github.com/pydantic/pydantic/pull/6816) * Fix link to mypy by [@progsmile](https://github.com/progsmile) in [#6824](https://github.com/pydantic/pydantic/pull/6824) * Improve initialization hooks example by [@hramezani](https://github.com/hramezani) in [#6822](https://github.com/pydantic/pydantic/pull/6822) * Fix default port for mongosrv DSNs by [@dmontagu](https://github.com/dmontagu) in [#6827](https://github.com/pydantic/pydantic/pull/6827) * Improve API documentation, in particular more links between usage and API docs by [@samuelcolvin](https://github.com/samuelcolvin) in [#6780](https://github.com/pydantic/pydantic/pull/6780) * update pydantic-core to 2.4.0 by [@davidhewitt](https://github.com/davidhewitt) in [#6831](https://github.com/pydantic/pydantic/pull/6831) * Fix `annotated_types.MaxLen` validator for custom sequence types by [@ImogenBits](https://github.com/ImogenBits) in [#6809](https://github.com/pydantic/pydantic/pull/6809) * Update V1 by [@hramezani](https://github.com/hramezani) in [#6833](https://github.com/pydantic/pydantic/pull/6833) * Make it so callable JSON schema extra works by [@dmontagu](https://github.com/dmontagu) in [#6798](https://github.com/pydantic/pydantic/pull/6798) * Fix serialization issue with `InstanceOf` by [@dmontagu](https://github.com/dmontagu) in [#6829](https://github.com/pydantic/pydantic/pull/6829) * Add back support for `json_encoders` by [@adriangb](https://github.com/adriangb) in [#6811](https://github.com/pydantic/pydantic/pull/6811) * Update field annotations when building the schema by [@dmontagu](https://github.com/dmontagu) in [#6838](https://github.com/pydantic/pydantic/pull/6838) * Use `WeakValueDictionary` to fix generic memory leak by [@dmontagu](https://github.com/dmontagu) in [#6681](https://github.com/pydantic/pydantic/pull/6681) * Add `config.defer_build` to optionally make model building lazy by [@samuelcolvin](https://github.com/samuelcolvin) in [#6823](https://github.com/pydantic/pydantic/pull/6823) * delegate `UUID` serialization to pydantic-core by [@davidhewitt](https://github.com/davidhewitt) in [#6850](https://github.com/pydantic/pydantic/pull/6850) * Update `json_encoders` docs by [@adriangb](https://github.com/adriangb) in [#6848](https://github.com/pydantic/pydantic/pull/6848) * Fix error message for `staticmethod`/`classmethod` order with validate\_call by [@dmontagu](https://github.com/dmontagu) in [#6686](https://github.com/pydantic/pydantic/pull/6686) * Improve documentation for `Config` by [@samuelcolvin](https://github.com/samuelcolvin) in [#6847](https://github.com/pydantic/pydantic/pull/6847) * Update serialization doc to mention `Field.exclude` takes priority over call-time `include/exclude` by [@hramezani](https://github.com/hramezani) in [#6851](https://github.com/pydantic/pydantic/pull/6851) * Allow customizing core schema generation by making `GenerateSchema` public by [@adriangb](https://github.com/adriangb) in [#6737](https://github.com/pydantic/pydantic/pull/6737) v2.0.3 (2023-07-05)[¶](#v203-2023-07-05 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.3) * Mention PyObject (v1) moving to ImportString (v2) in migration doc by [@slafs](https://github.com/slafs) in [#6456](https://github.com/pydantic/pydantic/pull/6456) * Fix release-tweet CI by [@Kludex](https://github.com/Kludex) in [#6461](https://github.com/pydantic/pydantic/pull/6461) * Revise the section on required / optional / nullable fields. by [@ybressler](https://github.com/ybressler) in [#6468](https://github.com/pydantic/pydantic/pull/6468) * Warn if a type hint is not in fact a type by [@adriangb](https://github.com/adriangb) in [#6479](https://github.com/pydantic/pydantic/pull/6479) * Replace TransformSchema with GetPydanticSchema by [@dmontagu](https://github.com/dmontagu) in [#6484](https://github.com/pydantic/pydantic/pull/6484) * Fix the un-hashability of various annotation types, for use in caching generic containers by [@dmontagu](https://github.com/dmontagu) in [#6480](https://github.com/pydantic/pydantic/pull/6480) * PYD-164: Rework custom types docs by [@adriangb](https://github.com/adriangb) in [#6490](https://github.com/pydantic/pydantic/pull/6490) * Fix ci by [@adriangb](https://github.com/adriangb) in [#6507](https://github.com/pydantic/pydantic/pull/6507) * Fix forward ref in generic by [@adriangb](https://github.com/adriangb) in [#6511](https://github.com/pydantic/pydantic/pull/6511) * Fix generation of serialization JSON schemas for core\_schema.ChainSchema by [@dmontagu](https://github.com/dmontagu) in [#6515](https://github.com/pydantic/pydantic/pull/6515) * Document the change in `Field.alias` behavior in Pydantic V2 by [@hramezani](https://github.com/hramezani) in [#6508](https://github.com/pydantic/pydantic/pull/6508) * Give better error message attempting to compute the json schema of a model with undefined fields by [@dmontagu](https://github.com/dmontagu) in [#6519](https://github.com/pydantic/pydantic/pull/6519) * Document `alias_priority` by [@tpdorsey](https://github.com/tpdorsey) in [#6520](https://github.com/pydantic/pydantic/pull/6520) * Add redirect for types documentation by [@tpdorsey](https://github.com/tpdorsey) in [#6513](https://github.com/pydantic/pydantic/pull/6513) * Allow updating docs without release by [@samuelcolvin](https://github.com/samuelcolvin) in [#6551](https://github.com/pydantic/pydantic/pull/6551) * Ensure docs tests always run in the right folder by [@dmontagu](https://github.com/dmontagu) in [#6487](https://github.com/pydantic/pydantic/pull/6487) * Defer evaluation of return type hints for serializer functions by [@dmontagu](https://github.com/dmontagu) in [#6516](https://github.com/pydantic/pydantic/pull/6516) * Disable E501 from Ruff and rely on just Black by [@adriangb](https://github.com/adriangb) in [#6552](https://github.com/pydantic/pydantic/pull/6552) * Update JSON Schema documentation for V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6492](https://github.com/pydantic/pydantic/pull/6492) * Add documentation of cyclic reference handling by [@dmontagu](https://github.com/dmontagu) in [#6493](https://github.com/pydantic/pydantic/pull/6493) * Remove the need for change files by [@samuelcolvin](https://github.com/samuelcolvin) in [#6556](https://github.com/pydantic/pydantic/pull/6556) * add "north star" benchmark by [@davidhewitt](https://github.com/davidhewitt) in [#6547](https://github.com/pydantic/pydantic/pull/6547) * Update Dataclasses docs by [@tpdorsey](https://github.com/tpdorsey) in [#6470](https://github.com/pydantic/pydantic/pull/6470) * ♻️ Use different error message on v1 redirects by [@Kludex](https://github.com/Kludex) in [#6595](https://github.com/pydantic/pydantic/pull/6595) * ⬆ Upgrade `pydantic-core` to v2.2.0 by [@lig](https://github.com/lig) in [#6589](https://github.com/pydantic/pydantic/pull/6589) * Fix serialization for IPvAny by [@dmontagu](https://github.com/dmontagu) in [#6572](https://github.com/pydantic/pydantic/pull/6572) * Improve CI by using PDM instead of pip to install typing-extensions by [@adriangb](https://github.com/adriangb) in [#6602](https://github.com/pydantic/pydantic/pull/6602) * Add `enum` error type docs by [@lig](https://github.com/lig) in [#6603](https://github.com/pydantic/pydantic/pull/6603) * 🐛 Fix `max_length` for unicode strings by [@lig](https://github.com/lig) in [#6559](https://github.com/pydantic/pydantic/pull/6559) * Add documentation for accessing features via `pydantic.v1` by [@tpdorsey](https://github.com/tpdorsey) in [#6604](https://github.com/pydantic/pydantic/pull/6604) * Include extra when iterating over a model by [@adriangb](https://github.com/adriangb) in [#6562](https://github.com/pydantic/pydantic/pull/6562) * Fix typing of model\_validator by [@adriangb](https://github.com/adriangb) in [#6514](https://github.com/pydantic/pydantic/pull/6514) * Touch up Decimal validator by [@adriangb](https://github.com/adriangb) in [#6327](https://github.com/pydantic/pydantic/pull/6327) * Fix various docstrings using fixed pytest-examples by [@dmontagu](https://github.com/dmontagu) in [#6607](https://github.com/pydantic/pydantic/pull/6607) * Handle function validators in a discriminated union by [@dmontagu](https://github.com/dmontagu) in [#6570](https://github.com/pydantic/pydantic/pull/6570) * Review json\_schema.md by [@tpdorsey](https://github.com/tpdorsey) in [#6608](https://github.com/pydantic/pydantic/pull/6608) * Make validate\_call work on basemodel methods by [@dmontagu](https://github.com/dmontagu) in [#6569](https://github.com/pydantic/pydantic/pull/6569) * add test for big int json serde by [@davidhewitt](https://github.com/davidhewitt) in [#6614](https://github.com/pydantic/pydantic/pull/6614) * Fix pydantic dataclass problem with dataclasses.field default\_factory by [@hramezani](https://github.com/hramezani) in [#6616](https://github.com/pydantic/pydantic/pull/6616) * Fixed mypy type inference for TypeAdapter by [@zakstucke](https://github.com/zakstucke) in [#6617](https://github.com/pydantic/pydantic/pull/6617) * Make it work to use None as a generic parameter by [@dmontagu](https://github.com/dmontagu) in [#6609](https://github.com/pydantic/pydantic/pull/6609) * Make it work to use `$ref` as an alias by [@dmontagu](https://github.com/dmontagu) in [#6568](https://github.com/pydantic/pydantic/pull/6568) * add note to migration guide about changes to `AnyUrl` etc by [@davidhewitt](https://github.com/davidhewitt) in [#6618](https://github.com/pydantic/pydantic/pull/6618) * 🐛 Support defining `json_schema_extra` on `RootModel` using `Field` by [@lig](https://github.com/lig) in [#6622](https://github.com/pydantic/pydantic/pull/6622) * Update pre-commit to prevent commits to main branch on accident by [@dmontagu](https://github.com/dmontagu) in [#6636](https://github.com/pydantic/pydantic/pull/6636) * Fix PDM CI for python 3.7 on MacOS/windows by [@dmontagu](https://github.com/dmontagu) in [#6627](https://github.com/pydantic/pydantic/pull/6627) * Produce more accurate signatures for pydantic dataclasses by [@dmontagu](https://github.com/dmontagu) in [#6633](https://github.com/pydantic/pydantic/pull/6633) * Updates to Url types for Pydantic V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6638](https://github.com/pydantic/pydantic/pull/6638) * Fix list markdown in `transform` docstring by [@StefanBRas](https://github.com/StefanBRas) in [#6649](https://github.com/pydantic/pydantic/pull/6649) * simplify slots\_dataclass construction to appease mypy by [@davidhewitt](https://github.com/davidhewitt) in [#6639](https://github.com/pydantic/pydantic/pull/6639) * Update TypedDict schema generation docstring by [@adriangb](https://github.com/adriangb) in [#6651](https://github.com/pydantic/pydantic/pull/6651) * Detect and lint-error for prints by [@dmontagu](https://github.com/dmontagu) in [#6655](https://github.com/pydantic/pydantic/pull/6655) * Add xfailing test for pydantic-core PR 766 by [@dmontagu](https://github.com/dmontagu) in [#6641](https://github.com/pydantic/pydantic/pull/6641) * Ignore unrecognized fields from dataclasses metadata by [@dmontagu](https://github.com/dmontagu) in [#6634](https://github.com/pydantic/pydantic/pull/6634) * Make non-existent class getattr a mypy error by [@dmontagu](https://github.com/dmontagu) in [#6658](https://github.com/pydantic/pydantic/pull/6658) * Update pydantic-core to 2.3.0 by [@hramezani](https://github.com/hramezani) in [#6648](https://github.com/pydantic/pydantic/pull/6648) * Use OrderedDict from typing\_extensions by [@dmontagu](https://github.com/dmontagu) in [#6664](https://github.com/pydantic/pydantic/pull/6664) * Fix typehint for JSON schema extra callable by [@dmontagu](https://github.com/dmontagu) in [#6659](https://github.com/pydantic/pydantic/pull/6659) v2.0.2 (2023-07-05)[¶](#v202-2023-07-05 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.2) * Fix bug where round-trip pickling/unpickling a `RootModel` would change the value of `__dict__`, [#6457](https://github.com/pydantic/pydantic/pull/6457) by [@dmontagu](https://github.com/dmontagu) * Allow single-item discriminated unions, [#6405](https://github.com/pydantic/pydantic/pull/6405) by [@dmontagu](https://github.com/dmontagu) * Fix issue with union parsing of enums, [#6440](https://github.com/pydantic/pydantic/pull/6440) by [@dmontagu](https://github.com/dmontagu) * Docs: Fixed `constr` documentation, renamed old `regex` to new `pattern`, [#6452](https://github.com/pydantic/pydantic/pull/6452) by [@miili](https://github.com/miili) * Change `GenerateJsonSchema.generate_definitions` signature, [#6436](https://github.com/pydantic/pydantic/pull/6436) by [@dmontagu](https://github.com/dmontagu) See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0.2) v2.0.1 (2023-07-04)[¶](#v201-2023-07-04 "Permanent link") ---------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.1) First patch release of Pydantic V2 * Extra fields added via `setattr` (i.e. `m.some_extra_field = 'extra_value'`) are added to `.model_extra` if `model_config` `extra='allowed'`. Fixed [#6333](https://github.com/pydantic/pydantic/pull/6333) , [#6365](https://github.com/pydantic/pydantic/pull/6365) by [@aaraney](https://github.com/aaraney) * Automatically unpack JSON schema '$ref' for custom types, [#6343](https://github.com/pydantic/pydantic/pull/6343) by [@adriangb](https://github.com/adriangb) * Fix tagged unions multiple processing in submodels, [#6340](https://github.com/pydantic/pydantic/pull/6340) by [@suharnikov](https://github.com/suharnikov) See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0.1) v2.0 (2023-06-30)[¶](#v20-2023-06-30 "Permanent link") ------------------------------------------------------- [GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0) Pydantic V2 is here! ![🎉](https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/svg/1f389.svg ":tada:") See [this post](https://docs.pydantic.dev/2.0/blog/pydantic-v2-final/) for more details. v2.0b3 (2023-06-16)[¶](#v20b3-2023-06-16 "Permanent link") ----------------------------------------------------------- Third beta pre-release of Pydantic V2 See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b3) v2.0b2 (2023-06-03)[¶](#v20b2-2023-06-03 "Permanent link") ----------------------------------------------------------- Add `from_attributes` runtime flag to `TypeAdapter.validate_python` and `BaseModel.model_validate`. See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b2) v2.0b1 (2023-06-01)[¶](#v20b1-2023-06-01 "Permanent link") ----------------------------------------------------------- First beta pre-release of Pydantic V2 See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b1) v2.0a4 (2023-05-05)[¶](#v20a4-2023-05-05 "Permanent link") ----------------------------------------------------------- Fourth pre-release of Pydantic V2 See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a4) v2.0a3 (2023-04-20)[¶](#v20a3-2023-04-20 "Permanent link") ----------------------------------------------------------- Third pre-release of Pydantic V2 See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a3) v2.0a2 (2023-04-12)[¶](#v20a2-2023-04-12 "Permanent link") ----------------------------------------------------------- Second pre-release of Pydantic V2 See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a2) v2.0a1 (2023-04-03)[¶](#v20a1-2023-04-03 "Permanent link") ----------------------------------------------------------- First pre-release of Pydantic V2! See [this post](https://docs.pydantic.dev/blog/pydantic-v2-alpha/) for more details. v1.10.21 (2025-01-10)[¶](#v11021-2025-01-10 "Permanent link") -------------------------------------------------------------- * Fix compatibility with ForwardRef.\_evaluate and Python < 3.12.4 by [@griels](https://github.com/griels) in https://github.com/pydantic/pydantic/pull/11232 v1.10.20 (2025-01-07)[¶](#v11020-2025-01-07 "Permanent link") -------------------------------------------------------------- This 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`. * General maintenance of CI and build ecosystem by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10847 * Update Cython to `3.0.x`. * Properly address Python 3.13 deprecation warnings. * Migrate packaging to `pyproject.toml`, make use of PEP 517 build options. * Use [`build`](https://pypi.org/project/build/) instead of direct `setup.py` invocations. * Update various Github Actions versions. * Replace outdated stpmex link in documentation by [@jaredenorris](https://github.com/jaredenorris) in https://github.com/pydantic/pydantic/pull/10997 v1.10.19 (2024-11-06)[¶](#v11019-2024-11-06 "Permanent link") -------------------------------------------------------------- * Add warning when v2 model is nested in v1 model by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10432 * Fix deprecation warning in V1 `isinstance` check by [@alicederyn](https://github.com/alicederyn) in https://github.com/pydantic/pydantic/pull/10645 v1.10.19 (2024-11-06)[¶](#v11019-2024-11-06_1 "Permanent link") ---------------------------------------------------------------- * Add warning when v2 model is nested in v1 model by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10432 * Fix deprecation warning in V1 `isinstance` check by [@alicederyn](https://github.com/alicederyn) in https://github.com/pydantic/pydantic/pull/10645 v1.10.18 (2024-08-22)[¶](#v11018-2024-08-22 "Permanent link") -------------------------------------------------------------- * Eval type fix in V1 by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/9751 * Add `to_lower_camel` to `__all__` in `utils.py` by [@sydney-runkle](https://github.com/sydney-runkle) (direct commit) * Fix `mypy` v1 plugin for mypy 1.11 release by [@flaeppe](https://github.com/flaeppe) in https://github.com/pydantic/pydantic/pull/10139 * Fix discriminator key used when discriminator has alias and `.schema(by_alias=False)` by [@exs-dwoodward](https://github.com/exs-dwoodward) in https://github.com/pydantic/pydantic/pull/10146 v1.10.17 (2024-06-20)[¶](#v11017-2024-06-20 "Permanent link") -------------------------------------------------------------- * Advertise Python 3.12 for 1.10.x! Part Deux by [@vfazio](https://github.com/vfazio) in https://github.com/pydantic/pydantic/pull/9644 * Mirrored modules in `v1` namespace to fix typing and object resolution in python>3.11 by [@exs-dwoodward](https://github.com/exs-dwoodward) in https://github.com/pydantic/pydantic/pull/9660 * setup: remove upper bound from python\_requires by [@vfazio](https://github.com/vfazio) in https://github.com/pydantic/pydantic/pull/9685 v1.10.16 (2024-06-11)[¶](#v11016-2024-06-11 "Permanent link") -------------------------------------------------------------- * Specify recursive\_guard as kwarg in FutureRef.\_evaluate by [@vfazio](https://github.com/vfazio) in https://github.com/pydantic/pydantic/pull/9612 * Fix mypy v1 plugin for upcoming mypy release by @ cdce8p in https://github.com/pydantic/pydantic/pull/9586 * Import modules/objects directly from v1 namespace by [@exs-dwoodward](https://github.com/exs-dwoodward) in https://github.com/pydantic/pydantic/pull/9162 v1.10.15 (2024-04-03)[¶](#v11015-2024-04-03 "Permanent link") -------------------------------------------------------------- * Add pydantic.v1 namespace to Pydantic v1 by [@exs-dmiketa](https://github.com/exs-dmiketa) in https://github.com/pydantic/pydantic/pull/9042 * Relax version of typing-extensions for V1 by [@SonOfLilit](https://github.com/SonOfLilit) in https://github.com/pydantic/pydantic/pull/8819 * patch fix for mypy by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/8765 v1.10.14 (2024-01-19)[¶](#v11014-2024-01-19 "Permanent link") -------------------------------------------------------------- * Update install.md by [@dmontagu](https://github.com/dmontagu) in #7690 * Fix ci to only deploy docs on release by [@sydney-runkle](https://github.com/sydney-runkle) in #7740 * Ubuntu fixes for V1 by [@sydney-runkle](https://github.com/sydney-runkle) in #8540 and #8587 * Fix cached\_property handling in dataclasses when copied by [@rdbisme](https://github.com/rdbisme) in #8407 v1.10.13 (2023-09-27)[¶](#v11013-2023-09-27 "Permanent link") -------------------------------------------------------------- * Fix: Add max length check to `pydantic.validate_email`, #7673 by [@hramezani](https://github.com/hramezani) * Docs: Fix pip commands to install v1, #6930 by [@chbndrhnns](https://github.com/chbndrhnns) v1.10.12 (2023-07-24)[¶](#v11012-2023-07-24 "Permanent link") -------------------------------------------------------------- * Fixes the `maxlen` property being dropped on `deque` validation. Happened only if the deque item has been typed. Changes the `_validate_sequence_like` func, [#6581](https://github.com/pydantic/pydantic/pull/6581) by [@maciekglowka](https://github.com/maciekglowka) v1.10.11 (2023-07-04)[¶](#v11011-2023-07-04 "Permanent link") -------------------------------------------------------------- * Importing create\_model in tools.py through relative path instead of absolute path - so that it doesn't import V2 code when copied over to V2 branch, [#6361](https://github.com/pydantic/pydantic/pull/6361) by [@SharathHuddar](https://github.com/SharathHuddar) v1.10.10 (2023-06-30)[¶](#v11010-2023-06-30 "Permanent link") -------------------------------------------------------------- * Add Pydantic `Json` field support to settings management, [#6250](https://github.com/pydantic/pydantic/pull/6250) by [@hramezani](https://github.com/hramezani) * Fixed literal validator errors for unhashable values, [#6188](https://github.com/pydantic/pydantic/pull/6188) by [@markus1978](https://github.com/markus1978) * Fixed bug with generics receiving forward refs, [#6130](https://github.com/pydantic/pydantic/pull/6130) by [@mark-todd](https://github.com/mark-todd) * Update install method of FastAPI for internal tests in CI, [#6117](https://github.com/pydantic/pydantic/pull/6117) by [@Kludex](https://github.com/Kludex) v1.10.9 (2023-06-07)[¶](#v1109-2023-06-07 "Permanent link") ------------------------------------------------------------ * Fix trailing zeros not ignored in Decimal validation, [#5968](https://github.com/pydantic/pydantic/pull/5968) by [@hramezani](https://github.com/hramezani) * Fix mypy plugin for v1.4.0, [#5928](https://github.com/pydantic/pydantic/pull/5928) by [@cdce8p](https://github.com/cdce8p) * Add future and past date hypothesis strategies, [#5850](https://github.com/pydantic/pydantic/pull/5850) by [@bschoenmaeckers](https://github.com/bschoenmaeckers) * Discourage usage of Cython 3 with Pydantic 1.x, [#5845](https://github.com/pydantic/pydantic/pull/5845) by [@lig](https://github.com/lig) v1.10.8 (2023-05-23)[¶](#v1108-2023-05-23 "Permanent link") ------------------------------------------------------------ * Fix a bug in `Literal` usage with `typing-extension==4.6.0`, [#5826](https://github.com/pydantic/pydantic/pull/5826) by [@hramezani](https://github.com/hramezani) * This solves the (closed) issue [#3849](https://github.com/pydantic/pydantic/pull/3849) where aliased fields that use discriminated union fail to validate when the data contains the non-aliased field name, [#5736](https://github.com/pydantic/pydantic/pull/5736) by [@benwah](https://github.com/benwah) * Update email-validator dependency to >=2.0.0post2, [#5627](https://github.com/pydantic/pydantic/pull/5627) by [@adriangb](https://github.com/adriangb) * update `AnyClassMethod` for changes in [python/typeshed#9771](https://github.com/python/typeshed/issues/9771) , [#5505](https://github.com/pydantic/pydantic/pull/5505) by [@ITProKyle](https://github.com/ITProKyle) v1.10.7 (2023-03-22)[¶](#v1107-2023-03-22 "Permanent link") ------------------------------------------------------------ * Fix creating schema from model using `ConstrainedStr` with `regex` as dict key, [#5223](https://github.com/pydantic/pydantic/pull/5223) by [@matejetz](https://github.com/matejetz) * Address bug in mypy plugin caused by explicit\_package\_bases=True, [#5191](https://github.com/pydantic/pydantic/pull/5191) by [@dmontagu](https://github.com/dmontagu) * Add implicit defaults in the mypy plugin for Field with no default argument, [#5190](https://github.com/pydantic/pydantic/pull/5190) by [@dmontagu](https://github.com/dmontagu) * Fix schema generated for Enum values used as Literals in discriminated unions, [#5188](https://github.com/pydantic/pydantic/pull/5188) by [@javibookline](https://github.com/javibookline) * Fix mypy failures caused by the pydantic mypy plugin when users define `from_orm` in their own classes, [#5187](https://github.com/pydantic/pydantic/pull/5187) by [@dmontagu](https://github.com/dmontagu) * Fix `InitVar` usage with pydantic dataclasses, mypy version `1.1.1` and the custom mypy plugin, [#5162](https://github.com/pydantic/pydantic/pull/5162) by [@cdce8p](https://github.com/cdce8p) v1.10.6 (2023-03-08)[¶](#v1106-2023-03-08 "Permanent link") ------------------------------------------------------------ * Implement logic to support creating validators from non standard callables by using defaults to identify them and unwrapping `functools.partial` and `functools.partialmethod` when checking the signature, [#5126](https://github.com/pydantic/pydantic/pull/5126) by [@JensHeinrich](https://github.com/JensHeinrich) * Fix mypy plugin for v1.1.1, and fix `dataclass_transform` decorator for pydantic dataclasses, [#5111](https://github.com/pydantic/pydantic/pull/5111) by [@cdce8p](https://github.com/cdce8p) * Raise `ValidationError`, not `ConfigError`, when a discriminator value is unhashable, [#4773](https://github.com/pydantic/pydantic/pull/4773) by [@kurtmckee](https://github.com/kurtmckee) v1.10.5 (2023-02-15)[¶](#v1105-2023-02-15 "Permanent link") ------------------------------------------------------------ * Fix broken parametrized bases handling with `GenericModel`s with complex sets of models, [#5052](https://github.com/pydantic/pydantic/pull/5052) by [@MarkusSintonen](https://github.com/MarkusSintonen) * Invalidate mypy cache if plugin config changes, [#5007](https://github.com/pydantic/pydantic/pull/5007) by [@cdce8p](https://github.com/cdce8p) * Fix `RecursionError` when deep-copying dataclass types wrapped by pydantic, [#4949](https://github.com/pydantic/pydantic/pull/4949) by [@mbillingr](https://github.com/mbillingr) * Fix `X | Y` union syntax breaking `GenericModel`, [#4146](https://github.com/pydantic/pydantic/pull/4146) by [@thenx](https://github.com/thenx) * Switch coverage badge to show coverage for this branch/release, [#5060](https://github.com/pydantic/pydantic/pull/5060) by [@samuelcolvin](https://github.com/samuelcolvin) v1.10.4 (2022-12-30)[¶](#v1104-2022-12-30 "Permanent link") ------------------------------------------------------------ * Change dependency to `typing-extensions>=4.2.0`, [#4885](https://github.com/pydantic/pydantic/pull/4885) by [@samuelcolvin](https://github.com/samuelcolvin) v1.10.3 (2022-12-29)[¶](#v1103-2022-12-29 "Permanent link") ------------------------------------------------------------ **NOTE: v1.10.3 was ["yanked"](https://pypi.org/help/#yanked) from PyPI due to [#4885](https://github.com/pydantic/pydantic/pull/4885) which is fixed in v1.10.4** * fix parsing of custom root models, [#4883](https://github.com/pydantic/pydantic/pull/4883) by [@gou177](https://github.com/gou177) * fix: use dataclass proxy for frozen or empty dataclasses, [#4878](https://github.com/pydantic/pydantic/pull/4878) by [@PrettyWood](https://github.com/PrettyWood) * Fix `schema` and `schema_json` on models where a model instance is a one of default values, [#4781](https://github.com/pydantic/pydantic/pull/4781) by [@Bobronium](https://github.com/Bobronium) * Add Jina AI to sponsors on docs index page, [#4767](https://github.com/pydantic/pydantic/pull/4767) by [@samuelcolvin](https://github.com/samuelcolvin) * fix: support assignment on `DataclassProxy`, [#4695](https://github.com/pydantic/pydantic/pull/4695) by [@PrettyWood](https://github.com/PrettyWood) * Add `postgresql+psycopg` as allowed scheme for `PostgreDsn` to make it usable with SQLAlchemy 2, [#4689](https://github.com/pydantic/pydantic/pull/4689) by [@morian](https://github.com/morian) * Allow dict schemas to have both `patternProperties` and `additionalProperties`, [#4641](https://github.com/pydantic/pydantic/pull/4641) by [@jparise](https://github.com/jparise) * Fixes error passing None for optional lists with `unique_items`, [#4568](https://github.com/pydantic/pydantic/pull/4568) by [@mfulgo](https://github.com/mfulgo) * Fix `GenericModel` with `Callable` param raising a `TypeError`, [#4551](https://github.com/pydantic/pydantic/pull/4551) by [@mfulgo](https://github.com/mfulgo) * Fix field regex with `StrictStr` type annotation, [#4538](https://github.com/pydantic/pydantic/pull/4538) by [@sisp](https://github.com/sisp) * Correct `dataclass_transform` keyword argument name from `field_descriptors` to `field_specifiers`, [#4500](https://github.com/pydantic/pydantic/pull/4500) by [@samuelcolvin](https://github.com/samuelcolvin) * fix: avoid multiple calls of `__post_init__` when dataclasses are inherited, [#4487](https://github.com/pydantic/pydantic/pull/4487) by [@PrettyWood](https://github.com/PrettyWood) * Reduce the size of binary wheels, [#2276](https://github.com/pydantic/pydantic/pull/2276) by [@samuelcolvin](https://github.com/samuelcolvin) v1.10.2 (2022-09-05)[¶](#v1102-2022-09-05 "Permanent link") ------------------------------------------------------------ * **Revert Change:** Revert percent encoding of URL parts which was originally added in [#4224](https://github.com/pydantic/pydantic/pull/4224) , [#4470](https://github.com/pydantic/pydantic/pull/4470) by [@samuelcolvin](https://github.com/samuelcolvin) * Prevent long (length > `4_300`) strings/bytes as input to int fields, see [python/cpython#95778](https://github.com/python/cpython/issues/95778) and [CVE-2020-10735](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735) , [#1477](https://github.com/pydantic/pydantic/pull/1477) by [@samuelcolvin](https://github.com/samuelcolvin) * fix: dataclass wrapper was not always called, [#4477](https://github.com/pydantic/pydantic/pull/4477) by [@PrettyWood](https://github.com/PrettyWood) * Use `tomllib` on Python 3.11 when parsing `mypy` configuration, [#4476](https://github.com/pydantic/pydantic/pull/4476) by [@hauntsaninja](https://github.com/hauntsaninja) * Basic fix of `GenericModel` cache to detect order of arguments in `Union` models, [#4474](https://github.com/pydantic/pydantic/pull/4474) by [@sveinugu](https://github.com/sveinugu) * Fix mypy plugin when using bare types like `list` and `dict` as `default_factory`, [#4457](https://github.com/pydantic/pydantic/pull/4457) by [@samuelcolvin](https://github.com/samuelcolvin) v1.10.1 (2022-08-31)[¶](#v1101-2022-08-31 "Permanent link") ------------------------------------------------------------ * Add `__hash__` method to `pydantic.color.Color` class, [#4454](https://github.com/pydantic/pydantic/pull/4454) by [@czaki](https://github.com/czaki) v1.10.0 (2022-08-30)[¶](#v1100-2022-08-30 "Permanent link") ------------------------------------------------------------ * Refactor 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](https://github.com/pydantic/pydantic/pull/2557) by [@PrettyWood](https://github.com/PrettyWood) **BREAKING CHANGES:** * The `compiled` boolean (whether _pydantic_ is compiled with cython) has been moved from `main.py` to `version.py` * Now that `Config.extra` is supported, `dataclass` ignores by default extra arguments (like `BaseModel`) * Fix PEP487 `__set_name__` protocol in `BaseModel` for PrivateAttrs, [#4407](https://github.com/pydantic/pydantic/pull/4407) by [@tlambert03](https://github.com/tlambert03) * Allow for custom parsing of environment variables via `parse_env_var` in `Config`, [#4406](https://github.com/pydantic/pydantic/pull/4406) by [@acmiyaguchi](https://github.com/acmiyaguchi) * Rename `master` to `main`, [#4405](https://github.com/pydantic/pydantic/pull/4405) by [@hramezani](https://github.com/hramezani) * Fix `StrictStr` does not raise `ValidationError` when `max_length` is present in `Field`, [#4388](https://github.com/pydantic/pydantic/pull/4388) by [@hramezani](https://github.com/hramezani) * Make `SecretStr` and `SecretBytes` hashable, [#4387](https://github.com/pydantic/pydantic/pull/4387) by [@chbndrhnns](https://github.com/chbndrhnns) * Fix `StrictBytes` does not raise `ValidationError` when `max_length` is present in `Field`, [#4380](https://github.com/pydantic/pydantic/pull/4380) by [@JeanArhancet](https://github.com/JeanArhancet) * Add support for bare `type`, [#4375](https://github.com/pydantic/pydantic/pull/4375) by [@hramezani](https://github.com/hramezani) * Support Python 3.11, including binaries for 3.11 in PyPI, [#4374](https://github.com/pydantic/pydantic/pull/4374) by [@samuelcolvin](https://github.com/samuelcolvin) * Add support for `re.Pattern`, [#4366](https://github.com/pydantic/pydantic/pull/4366) by [@hramezani](https://github.com/hramezani) * Fix `__post_init_post_parse__` is incorrectly passed keyword arguments when no `__post_init__` is defined, [#4361](https://github.com/pydantic/pydantic/pull/4361) by [@hramezani](https://github.com/hramezani) * Fix implicitly importing `ForwardRef` and `Callable` from `pydantic.typing` instead of `typing` and also expose `MappingIntStrAny`, [#4358](https://github.com/pydantic/pydantic/pull/4358) by [@aminalaee](https://github.com/aminalaee) * remove `Any` types from the `dataclass` decorator so it can be used with the `disallow_any_expr` mypy option, [#4356](https://github.com/pydantic/pydantic/pull/4356) by [@DetachHead](https://github.com/DetachHead) * moved repo to `pydantic/pydantic`, [#4348](https://github.com/pydantic/pydantic/pull/4348) by [@yezz123](https://github.com/yezz123) * fix "extra fields not permitted" error when dataclass with `Extra.forbid` is validated multiple times, [#4343](https://github.com/pydantic/pydantic/pull/4343) by [@detachhead](https://github.com/detachhead) * Add Python 3.9 and 3.10 examples to docs, [#4339](https://github.com/pydantic/pydantic/pull/4339) by [@Bobronium](https://github.com/Bobronium) * Discriminated union models now use `oneOf` instead of `anyOf` when generating OpenAPI schema definitions, [#4335](https://github.com/pydantic/pydantic/pull/4335) by [@MaxwellPayne](https://github.com/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](https://github.com/pydantic/pydantic/pull/4332) by [@Bobronium](https://github.com/Bobronium) * Allow empty string aliases by using a `alias is not None` check, rather than `bool(alias)`, [#4253](https://github.com/pydantic/pydantic/pull/4253) by [@sergeytsaplin](https://github.com/sergeytsaplin) * Update `ForwardRef`s in `Field.outer_type_`, [#4249](https://github.com/pydantic/pydantic/pull/4249) by [@JacobHayes](https://github.com/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](https://peps.python.org/pep-0681/) , [#4241](https://github.com/pydantic/pydantic/pull/4241) by [@multimeric](https://github.com/multimeric) * Use parent model's `Config` when validating nested `NamedTuple` fields, [#4219](https://github.com/pydantic/pydantic/pull/4219) by [@synek](https://github.com/synek) * Update `BaseModel.construct` to work with aliased Fields, [#4192](https://github.com/pydantic/pydantic/pull/4192) by [@kylebamos](https://github.com/kylebamos) * Catch certain raised errors in `smart_deepcopy` and revert to `deepcopy` if so, [#4184](https://github.com/pydantic/pydantic/pull/4184) by [@coneybeare](https://github.com/coneybeare) * Add `Config.anystr_upper` and `to_upper` kwarg to constr and conbytes, [#4165](https://github.com/pydantic/pydantic/pull/4165) by [@satheler](https://github.com/satheler) * Fix JSON schema for `set` and `frozenset` when they include default values, [#4155](https://github.com/pydantic/pydantic/pull/4155) by [@aminalaee](https://github.com/aminalaee) * Teach the mypy plugin that methods decorated by `@validator` are classmethods, [#4102](https://github.com/pydantic/pydantic/pull/4102) by [@DMRobertson](https://github.com/DMRobertson) * Improve mypy plugin's ability to detect required fields, [#4086](https://github.com/pydantic/pydantic/pull/4086) by [@richardxia](https://github.com/richardxia) * Support fields of type `Type[]` in schema, [#4051](https://github.com/pydantic/pydantic/pull/4051) by [@aminalaee](https://github.com/aminalaee) * Add `default` value in JSON Schema when `const=True`, [#4031](https://github.com/pydantic/pydantic/pull/4031) by [@aminalaee](https://github.com/aminalaee) * Adds reserved word check to signature generation logic, [#4011](https://github.com/pydantic/pydantic/pull/4011) by [@strue36](https://github.com/strue36) * Fix Json strategy failure for the complex nested field, [#4005](https://github.com/pydantic/pydantic/pull/4005) by [@sergiosim](https://github.com/sergiosim) * Add JSON-compatible float constraint `allow_inf_nan`, [#3994](https://github.com/pydantic/pydantic/pull/3994) by [@tiangolo](https://github.com/tiangolo) * Remove undefined behaviour when `env_prefix` had characters in common with `env_nested_delimiter`, [#3975](https://github.com/pydantic/pydantic/pull/3975) by [@arsenron](https://github.com/arsenron) * Support generics model with `create_model`, [#3945](https://github.com/pydantic/pydantic/pull/3945) by [@hot123s](https://github.com/hot123s) * allow submodels to overwrite extra field info, [#3934](https://github.com/pydantic/pydantic/pull/3934) by [@PrettyWood](https://github.com/PrettyWood) * Document and test structural pattern matching ([PEP 636](https://peps.python.org/pep-0636/) ) on `BaseModel`, [#3920](https://github.com/pydantic/pydantic/pull/3920) by [@irgolic](https://github.com/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](https://github.com/pydantic/pydantic/pull/3899) by [@07pepa](https://github.com/07pepa) * Fix validation of discriminated union fields with an alias when passing a model instance, [#3846](https://github.com/pydantic/pydantic/pull/3846) by [@chornsby](https://github.com/chornsby) * Add a CockroachDsn type to validate CockroachDB connection strings. The type supports the following schemes: `cockroachdb`, `cockroachdb+psycopg2` and `cockroachdb+asyncpg`, [#3839](https://github.com/pydantic/pydantic/pull/3839) by [@blubber](https://github.com/blubber) * Fix MyPy plugin to not override pre-existing `__init__` method in models, [#3824](https://github.com/pydantic/pydantic/pull/3824) by [@patrick91](https://github.com/patrick91) * Fix mypy version checking, [#3783](https://github.com/pydantic/pydantic/pull/3783) by [@KotlinIsland](https://github.com/KotlinIsland) * support overwriting dunder attributes of `BaseModel` instances, [#3777](https://github.com/pydantic/pydantic/pull/3777) by [@PrettyWood](https://github.com/PrettyWood) * Added `ConstrainedDate` and `condate`, [#3740](https://github.com/pydantic/pydantic/pull/3740) by [@hottwaj](https://github.com/hottwaj) * Support `kw_only` in dataclasses, [#3670](https://github.com/pydantic/pydantic/pull/3670) by [@detachhead](https://github.com/detachhead) * Add comparison method for `Color` class, [#3646](https://github.com/pydantic/pydantic/pull/3646) by [@aminalaee](https://github.com/aminalaee) * Drop support for python3.6, associated cleanup, [#3605](https://github.com/pydantic/pydantic/pull/3605) by [@samuelcolvin](https://github.com/samuelcolvin) * created new function `to_lower_camel()` for "non pascal case" camel case, [#3463](https://github.com/pydantic/pydantic/pull/3463) by [@schlerp](https://github.com/schlerp) * Add checks to `default` and `default_factory` arguments in Mypy plugin, [#3430](https://github.com/pydantic/pydantic/pull/3430) by [@klaa97](https://github.com/klaa97) * fix mangling of `inspect.signature` for `BaseModel`, [#3413](https://github.com/pydantic/pydantic/pull/3413) by [@fix-inspect-signature](https://github.com/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](https://github.com/pydantic/pydantic/pull/3409) by [@expobrain](https://github.com/expobrain) * Support multi hosts validation in `PostgresDsn`, [#3337](https://github.com/pydantic/pydantic/pull/3337) by [@rglsk](https://github.com/rglsk) * Fix parsing of very small numeric timedelta values, [#3315](https://github.com/pydantic/pydantic/pull/3315) by [@samuelcolvin](https://github.com/samuelcolvin) * Update `SecretsSettingsSource` to respect `config.case_sensitive`, [#3273](https://github.com/pydantic/pydantic/pull/3273) by [@JeanArhancet](https://github.com/JeanArhancet) * Add MongoDB network data source name (DSN) schema, [#3229](https://github.com/pydantic/pydantic/pull/3229) by [@snosratiershad](https://github.com/snosratiershad) * Add support for multiple dotenv files, [#3222](https://github.com/pydantic/pydantic/pull/3222) by [@rekyungmin](https://github.com/rekyungmin) * Raise an explicit `ConfigError` when multiple fields are incorrectly set for a single validator, [#3215](https://github.com/pydantic/pydantic/pull/3215) by [@SunsetOrange](https://github.com/SunsetOrange) * Allow ellipsis on `Field`s inside `Annotated` for `TypedDicts` required, [#3133](https://github.com/pydantic/pydantic/pull/3133) by [@ezegomez](https://github.com/ezegomez) * Catch overflow errors in `int_validator`, [#3112](https://github.com/pydantic/pydantic/pull/3112) by [@ojii](https://github.com/ojii) * Adds a `__rich_repr__` method to `Representation` class which enables pretty printing with [Rich](https://github.com/willmcgugan/rich) , [#3099](https://github.com/pydantic/pydantic/pull/3099) by [@willmcgugan](https://github.com/willmcgugan) * Add percent encoding in `AnyUrl` and descendent types, [#3061](https://github.com/pydantic/pydantic/pull/3061) by [@FaresAhmedb](https://github.com/FaresAhmedb) * `validate_arguments` decorator now supports `alias`, [#3019](https://github.com/pydantic/pydantic/pull/3019) by [@MAD-py](https://github.com/MAD-py) * Avoid `__dict__` and `__weakref__` attributes in `AnyUrl` and IP address fields, [#2890](https://github.com/pydantic/pydantic/pull/2890) by [@nuno-andre](https://github.com/nuno-andre) * Add ability to use `Final` in a field type annotation, [#2766](https://github.com/pydantic/pydantic/pull/2766) by [@uriyyo](https://github.com/uriyyo) * Update requirement to `typing_extensions>=4.1.0` to guarantee `dataclass_transform` is available, [#4424](https://github.com/pydantic/pydantic/pull/4424) by [@commonism](https://github.com/commonism) * Add Explosion and AWS to main sponsors, [#4413](https://github.com/pydantic/pydantic/pull/4413) by [@samuelcolvin](https://github.com/samuelcolvin) * Update documentation for `copy_on_model_validation` to reflect recent changes, [#4369](https://github.com/pydantic/pydantic/pull/4369) by [@samuelcolvin](https://github.com/samuelcolvin) * Runtime warning if `__slots__` is passed to `create_model`, `__slots__` is then ignored, [#4432](https://github.com/pydantic/pydantic/pull/4432) by [@samuelcolvin](https://github.com/samuelcolvin) * Add type hints to `BaseSettings.Config` to avoid mypy errors, also correct mypy version compatibility notice in docs, [#4450](https://github.com/pydantic/pydantic/pull/4450) by [@samuelcolvin](https://github.com/samuelcolvin) v1.10.0b1 (2022-08-24)[¶](#v1100b1-2022-08-24 "Permanent link") ---------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v1.10.0b1) for details. v1.10.0a2 (2022-08-24)[¶](#v1100a2-2022-08-24 "Permanent link") ---------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v1.10.0a2) for details. v1.10.0a1 (2022-08-22)[¶](#v1100a1-2022-08-22 "Permanent link") ---------------------------------------------------------------- Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v1.10.0a1) for details. v1.9.2 (2022-08-11)[¶](#v192-2022-08-11 "Permanent link") ---------------------------------------------------------- **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](https://github.com/pydantic/pydantic/pull/4092) for more information. * Allow for shallow copies of model fields, `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](https://github.com/pydantic/pydantic/pull/4093) by [@timkpaine](https://github.com/timkpaine) v1.9.1 (2022-05-19)[¶](#v191-2022-05-19 "Permanent link") ---------------------------------------------------------- Thank you to pydantic's sponsors: [@tiangolo](https://github.com/tiangolo) , [@stellargraph](https://github.com/stellargraph) , [@JonasKs](https://github.com/JonasKs) , [@grillazz](https://github.com/grillazz) , [@Mazyod](https://github.com/Mazyod) , [@kevinalh](https://github.com/kevinalh) , [@chdsbd](https://github.com/chdsbd) , [@povilasb](https://github.com/povilasb) , [@povilasb](https://github.com/povilasb) , [@jina-ai](https://github.com/jina-ai) , [@mainframeindustries](https://github.com/mainframeindustries) , [@robusta-dev](https://github.com/robusta-dev) , [@SendCloud](https://github.com/SendCloud) , [@rszamszur](https://github.com/rszamszur) , [@jodal](https://github.com/jodal) , [@hardbyte](https://github.com/hardbyte) , [@corleyma](https://github.com/corleyma) , [@daddycocoaman](https://github.com/daddycocoaman) , [@Rehket](https://github.com/Rehket) , [@jokull](https://github.com/jokull) , [@reillysiemens](https://github.com/reillysiemens) , [@westonsteimel](https://github.com/westonsteimel) , [@primer-io](https://github.com/primer-io) , [@koxudaxi](https://github.com/koxudaxi) , [@browniebroke](https://github.com/browniebroke) , [@stradivari96](https://github.com/stradivari96) , [@adriangb](https://github.com/adriangb) , [@kamalgill](https://github.com/kamalgill) , [@jqueguiner](https://github.com/jqueguiner) , [@dev-zero](https://github.com/dev-zero) , [@datarootsio](https://github.com/datarootsio) , [@RedCarpetUp](https://github.com/RedCarpetUp) for their kind support. * Limit the size of `generics._generic_types_cache` and `generics._assigned_parameters` to avoid unlimited increase in memory usage, [#4083](https://github.com/pydantic/pydantic/pull/4083) by [@samuelcolvin](https://github.com/samuelcolvin) * Add Jupyverse and FPS as Jupyter projects using pydantic, [#4082](https://github.com/pydantic/pydantic/pull/4082) by [@davidbrochart](https://github.com/davidbrochart) * Speedup `__isinstancecheck__` on pydantic models when the type is not a model, may also avoid memory "leaks", [#4081](https://github.com/pydantic/pydantic/pull/4081) by [@samuelcolvin](https://github.com/samuelcolvin) * Fix in-place modification of `FieldInfo` that caused problems with PEP 593 type aliases, [#4067](https://github.com/pydantic/pydantic/pull/4067) by [@adriangb](https://github.com/adriangb) * Add support for autocomplete in VS Code via `__dataclass_transform__` when using `pydantic.dataclasses.dataclass`, [#4006](https://github.com/pydantic/pydantic/pull/4006) by [@giuliano-oliveira](https://github.com/giuliano-oliveira) * Remove benchmarks from codebase and docs, [#3973](https://github.com/pydantic/pydantic/pull/3973) by [@samuelcolvin](https://github.com/samuelcolvin) * Typing checking with pyright in CI, improve docs on vscode/pylance/pyright, [#3972](https://github.com/pydantic/pydantic/pull/3972) by [@samuelcolvin](https://github.com/samuelcolvin) * Fix nested Python dataclass schema regression, [#3819](https://github.com/pydantic/pydantic/pull/3819) by [@himbeles](https://github.com/himbeles) * Update documentation about lazy evaluation of sources for Settings, [#3806](https://github.com/pydantic/pydantic/pull/3806) by [@garyd203](https://github.com/garyd203) * Prevent subclasses of bytes being converted to bytes, [#3706](https://github.com/pydantic/pydantic/pull/3706) by [@samuelcolvin](https://github.com/samuelcolvin) * Fixed "error checking inheritance of" when using PEP585 and PEP604 type hints, [#3681](https://github.com/pydantic/pydantic/pull/3681) by [@aleksul](https://github.com/aleksul) * Allow self referencing `ClassVar`s in models, [#3679](https://github.com/pydantic/pydantic/pull/3679) by [@samuelcolvin](https://github.com/samuelcolvin) * **Breaking Change, see [#4106](https://github.com/pydantic/pydantic/pull/4106) **: Fix issue with self-referencing dataclass, [#3675](https://github.com/pydantic/pydantic/pull/3675) by [@uriyyo](https://github.com/uriyyo) * Include non-standard port numbers in rendered URLs, [#3652](https://github.com/pydantic/pydantic/pull/3652) by [@dolfinus](https://github.com/dolfinus) * `Config.copy_on_model_validation` does a deep copy and not a shallow one, [#3641](https://github.com/pydantic/pydantic/pull/3641) by [@PrettyWood](https://github.com/PrettyWood) * fix: clarify that discriminated unions do not support singletons, [#3636](https://github.com/pydantic/pydantic/pull/3636) by [@tommilligan](https://github.com/tommilligan) * Add `read_text(encoding='utf-8')` for `setup.py`, [#3625](https://github.com/pydantic/pydantic/pull/3625) by [@hswong3i](https://github.com/hswong3i) * Fix JSON Schema generation for Discriminated Unions within lists, [#3608](https://github.com/pydantic/pydantic/pull/3608) by [@samuelcolvin](https://github.com/samuelcolvin) v1.9.0 (2021-12-31)[¶](#v190-2021-12-31 "Permanent link") ---------------------------------------------------------- Thank you to pydantic's sponsors: [@sthagen](https://github.com/sthagen) , [@timdrijvers](https://github.com/timdrijvers) , [@toinbis](https://github.com/toinbis) , [@koxudaxi](https://github.com/koxudaxi) , [@ginomempin](https://github.com/ginomempin) , [@primer-io](https://github.com/primer-io) , [@and-semakin](https://github.com/and-semakin) , [@westonsteimel](https://github.com/westonsteimel) , [@reillysiemens](https://github.com/reillysiemens) , [@es3n1n](https://github.com/es3n1n) , [@jokull](https://github.com/jokull) , [@JonasKs](https://github.com/JonasKs) , [@Rehket](https://github.com/Rehket) , [@corleyma](https://github.com/corleyma) , [@daddycocoaman](https://github.com/daddycocoaman) , [@hardbyte](https://github.com/hardbyte) , [@datarootsio](https://github.com/datarootsio) , [@jodal](https://github.com/jodal) , [@aminalaee](https://github.com/aminalaee) , [@rafsaf](https://github.com/rafsaf) , [@jqueguiner](https://github.com/jqueguiner) , [@chdsbd](https://github.com/chdsbd) , [@kevinalh](https://github.com/kevinalh) , [@Mazyod](https://github.com/Mazyod) , [@grillazz](https://github.com/grillazz) , [@JonasKs](https://github.com/JonasKs) , [@simw](https://github.com/simw) , [@leynier](https://github.com/leynier) , [@xfenix](https://github.com/xfenix) for their kind support. ### Highlights[¶](#highlights "Permanent link") * add Python 3.10 support, [#2885](https://github.com/pydantic/pydantic/pull/2885) by [@PrettyWood](https://github.com/PrettyWood) * [Discriminated unions](https://docs.pydantic.dev/usage/types/#discriminated-unions-aka-tagged-unions) , [#619](https://github.com/pydantic/pydantic/pull/619) by [@PrettyWood](https://github.com/PrettyWood) * [`Config.smart_union` for better union logic](https://docs.pydantic.dev/usage/model_config/#smart-union) , [#2092](https://github.com/pydantic/pydantic/pull/2092) by [@PrettyWood](https://github.com/PrettyWood) * Binaries for Macos M1 CPUs, [#3498](https://github.com/pydantic/pydantic/pull/3498) by [@samuelcolvin](https://github.com/samuelcolvin) * Complex types can be set via [nested environment variables](https://docs.pydantic.dev/usage/settings/#parsing-environment-variable-values) , e.g. `foo___bar`, [#3159](https://github.com/pydantic/pydantic/pull/3159) by [@Air-Mark](https://github.com/Air-Mark) * add a dark mode to _pydantic_ documentation, [#2913](https://github.com/pydantic/pydantic/pull/2913) by [@gbdlin](https://github.com/gbdlin) * Add support for autocomplete in VS Code via `__dataclass_transform__`, [#2721](https://github.com/pydantic/pydantic/pull/2721) by [@tiangolo](https://github.com/tiangolo) * Add "exclude" as a field parameter so that it can be configured using model config, [#660](https://github.com/pydantic/pydantic/pull/660) by [@daviskirk](https://github.com/daviskirk) ### v1.9.0 (2021-12-31) Changes[¶](#v190-2021-12-31-changes "Permanent link") * Apply `update_forward_refs` to `Config.json_encodes` prevent name clashes in types defined via strings, [#3583](https://github.com/pydantic/pydantic/pull/3583) by [@samuelcolvin](https://github.com/samuelcolvin) * Extend pydantic's mypy plugin to support mypy versions `0.910`, `0.920`, `0.921` & `0.930`, [#3573](https://github.com/pydantic/pydantic/pull/3573) & [#3594](https://github.com/pydantic/pydantic/pull/3594) by [@PrettyWood](https://github.com/PrettyWood) , [@christianbundy](https://github.com/christianbundy) , [@samuelcolvin](https://github.com/samuelcolvin) ### v1.9.0a2 (2021-12-24) Changes[¶](#v190a2-2021-12-24-changes "Permanent link") * support generic models with discriminated union, [#3551](https://github.com/pydantic/pydantic/pull/3551) by [@PrettyWood](https://github.com/PrettyWood) * keep old behaviour of `json()` by default, [#3542](https://github.com/pydantic/pydantic/pull/3542) by [@PrettyWood](https://github.com/PrettyWood) * Removed typing-only `__root__` attribute from `BaseModel`, [#3540](https://github.com/pydantic/pydantic/pull/3540) by [@layday](https://github.com/layday) * Build Python 3.10 wheels, [#3539](https://github.com/pydantic/pydantic/pull/3539) by [@mbachry](https://github.com/mbachry) * Fix display of `extra` fields with model `__repr__`, [#3234](https://github.com/pydantic/pydantic/pull/3234) by [@cocolman](https://github.com/cocolman) * models copied via `Config.copy_on_model_validation` always have all fields, [#3201](https://github.com/pydantic/pydantic/pull/3201) by [@PrettyWood](https://github.com/PrettyWood) * nested ORM from nested dictionaries, [#3182](https://github.com/pydantic/pydantic/pull/3182) by [@PrettyWood](https://github.com/PrettyWood) * fix link to discriminated union section by [@PrettyWood](https://github.com/PrettyWood) ### v1.9.0a1 (2021-12-18) Changes[¶](#v190a1-2021-12-18-changes "Permanent link") * Add support for `Decimal`\-specific validation configurations in `Field()`, additionally to using `condecimal()`, to allow better support from editors and tooling, [#3507](https://github.com/pydantic/pydantic/pull/3507) by [@tiangolo](https://github.com/tiangolo) * Add `arm64` binaries suitable for MacOS with an M1 CPU to PyPI, [#3498](https://github.com/pydantic/pydantic/pull/3498) by [@samuelcolvin](https://github.com/samuelcolvin) * Fix issue where `None` was considered invalid when using a `Union` type containing `Any` or `object`, [#3444](https://github.com/pydantic/pydantic/pull/3444) by [@tharradine](https://github.com/tharradine) * When generating field schema, pass optional `field` argument (of type `pydantic.fields.ModelField`) to `__modify_schema__()` if present, [#3434](https://github.com/pydantic/pydantic/pull/3434) by [@jasujm](https://github.com/jasujm) * Fix issue when pydantic fail to parse `typing.ClassVar` string type annotation, [#3401](https://github.com/pydantic/pydantic/pull/3401) by [@uriyyo](https://github.com/uriyyo) * Mention Python >= 3.9.2 as an alternative to `typing_extensions.TypedDict`, [#3374](https://github.com/pydantic/pydantic/pull/3374) by [@BvB93](https://github.com/BvB93) * Changed the validator method name in the [Custom Errors example](https://docs.pydantic.dev/usage/models/#custom-errors) to more accurately describe what the validator is doing; changed from `name_must_contain_space` to `value_must_equal_bar`, [#3327](https://github.com/pydantic/pydantic/pull/3327) by [@michaelrios28](https://github.com/michaelrios28) * Add `AmqpDsn` class, [#3254](https://github.com/pydantic/pydantic/pull/3254) by [@kludex](https://github.com/kludex) * Always use `Enum` value as default in generated JSON schema, [#3190](https://github.com/pydantic/pydantic/pull/3190) by [@joaommartins](https://github.com/joaommartins) * Add support for Mypy 0.920, [#3175](https://github.com/pydantic/pydantic/pull/3175) by [@christianbundy](https://github.com/christianbundy) * `validate_arguments` now supports `extra` customization (used to always be `Extra.forbid`), [#3161](https://github.com/pydantic/pydantic/pull/3161) by [@PrettyWood](https://github.com/PrettyWood) * Complex types can be set by nested environment variables, [#3159](https://github.com/pydantic/pydantic/pull/3159) by [@Air-Mark](https://github.com/Air-Mark) * Fix mypy plugin to collect fields based on `pydantic.utils.is_valid_field` so that it ignores untyped private variables, [#3146](https://github.com/pydantic/pydantic/pull/3146) by [@hi-ogawa](https://github.com/hi-ogawa) * fix `validate_arguments` issue with `Config.validate_all`, [#3135](https://github.com/pydantic/pydantic/pull/3135) by [@PrettyWood](https://github.com/PrettyWood) * avoid dict coercion when using dict subclasses as field type, [#3122](https://github.com/pydantic/pydantic/pull/3122) by [@PrettyWood](https://github.com/PrettyWood) * add support for `object` type, [#3062](https://github.com/pydantic/pydantic/pull/3062) by [@PrettyWood](https://github.com/PrettyWood) * Updates pydantic dataclasses to keep `_special` properties on parent classes, [#3043](https://github.com/pydantic/pydantic/pull/3043) by [@zulrang](https://github.com/zulrang) * Add a `TypedDict` class for error objects, [#3038](https://github.com/pydantic/pydantic/pull/3038) by [@matthewhughes934](https://github.com/matthewhughes934) * Fix support for using a subclass of an annotation as a default, [#3018](https://github.com/pydantic/pydantic/pull/3018) by [@JacobHayes](https://github.com/JacobHayes) * make `create_model_from_typeddict` mypy compliant, [#3008](https://github.com/pydantic/pydantic/pull/3008) by [@PrettyWood](https://github.com/PrettyWood) * Make multiple inheritance work when using `PrivateAttr`, [#2989](https://github.com/pydantic/pydantic/pull/2989) by [@hmvp](https://github.com/hmvp) * Parse environment variables as JSON, if they have a `Union` type with a complex subfield, [#2936](https://github.com/pydantic/pydantic/pull/2936) by [@cbartz](https://github.com/cbartz) * Prevent `StrictStr` permitting `Enum` values where the enum inherits from `str`, [#2929](https://github.com/pydantic/pydantic/pull/2929) by [@samuelcolvin](https://github.com/samuelcolvin) * Make `SecretsSettingsSource` parse values being assigned to fields of complex types when sourced from a secrets file, just as when sourced from environment variables, [#2917](https://github.com/pydantic/pydantic/pull/2917) by [@davidmreed](https://github.com/davidmreed) * add a dark mode to _pydantic_ documentation, [#2913](https://github.com/pydantic/pydantic/pull/2913) by [@gbdlin](https://github.com/gbdlin) * Make `pydantic-mypy` plugin compatible with `pyproject.toml` configuration, consistent with `mypy` changes. See the [doc](https://docs.pydantic.dev/mypy_plugin/#configuring-the-plugin) for more information, [#2908](https://github.com/pydantic/pydantic/pull/2908) by [@jrwalk](https://github.com/jrwalk) * add Python 3.10 support, [#2885](https://github.com/pydantic/pydantic/pull/2885) by [@PrettyWood](https://github.com/PrettyWood) * Correctly parse generic models with `Json[T]`, [#2860](https://github.com/pydantic/pydantic/pull/2860) by [@geekingfrog](https://github.com/geekingfrog) * Update contrib docs re: Python version to use for building docs, [#2856](https://github.com/pydantic/pydantic/pull/2856) by [@paxcodes](https://github.com/paxcodes) * Clarify documentation about _pydantic_'s support for custom validation and strict type checking, despite _pydantic_ being primarily a parsing library, [#2855](https://github.com/pydantic/pydantic/pull/2855) by [@paxcodes](https://github.com/paxcodes) * Fix schema generation for `Deque` fields, [#2810](https://github.com/pydantic/pydantic/pull/2810) by [@sergejkozin](https://github.com/sergejkozin) * fix an edge case when mixing constraints and `Literal`, [#2794](https://github.com/pydantic/pydantic/pull/2794) by [@PrettyWood](https://github.com/PrettyWood) * Fix postponed annotation resolution for `NamedTuple` and `TypedDict` when they're used directly as the type of fields within Pydantic models, [#2760](https://github.com/pydantic/pydantic/pull/2760) by [@jameysharp](https://github.com/jameysharp) * Fix bug when `mypy` plugin fails on `construct` method call for `BaseSettings` derived classes, [#2753](https://github.com/pydantic/pydantic/pull/2753) by [@uriyyo](https://github.com/uriyyo) * Add function overloading for a `pydantic.create_model` function, [#2748](https://github.com/pydantic/pydantic/pull/2748) by [@uriyyo](https://github.com/uriyyo) * Fix mypy plugin issue with self field declaration, [#2743](https://github.com/pydantic/pydantic/pull/2743) by [@uriyyo](https://github.com/uriyyo) * The colon at the end of the line "The fields which were supplied when user was initialised:" suggests that the code following it is related. Changed it to a period, [#2733](https://github.com/pydantic/pydantic/pull/2733) by [@krisaoe](https://github.com/krisaoe) * Renamed variable `schema` to `schema_` to avoid shadowing of global variable name, [#2724](https://github.com/pydantic/pydantic/pull/2724) by [@shahriyarr](https://github.com/shahriyarr) * Add support for autocomplete in VS Code via `__dataclass_transform__`, [#2721](https://github.com/pydantic/pydantic/pull/2721) by [@tiangolo](https://github.com/tiangolo) * add missing type annotations in `BaseConfig` and handle `max_length = 0`, [#2719](https://github.com/pydantic/pydantic/pull/2719) by [@PrettyWood](https://github.com/PrettyWood) * Change `orm_mode` checking to allow recursive ORM mode parsing with dicts, [#2718](https://github.com/pydantic/pydantic/pull/2718) by [@nuno-andre](https://github.com/nuno-andre) * Add episode 313 of the _Talk Python To Me_ podcast, where Michael Kennedy and Samuel Colvin discuss Pydantic, to the docs, [#2712](https://github.com/pydantic/pydantic/pull/2712) by [@RatulMaharaj](https://github.com/RatulMaharaj) * fix JSON schema generation when a field is of type `NamedTuple` and has a default value, [#2707](https://github.com/pydantic/pydantic/pull/2707) by [@PrettyWood](https://github.com/PrettyWood) * `Enum` fields now properly support extra kwargs in schema generation, [#2697](https://github.com/pydantic/pydantic/pull/2697) by [@sammchardy](https://github.com/sammchardy) * **Breaking Change, see [#3780](https://github.com/pydantic/pydantic/pull/3780) **: Make serialization of referenced pydantic models possible, [#2650](https://github.com/pydantic/pydantic/pull/2650) by [@PrettyWood](https://github.com/PrettyWood) * Add `uniqueItems` option to `ConstrainedList`, [#2618](https://github.com/pydantic/pydantic/pull/2618) by [@nuno-andre](https://github.com/nuno-andre) * Try to evaluate forward refs automatically at model creation, [#2588](https://github.com/pydantic/pydantic/pull/2588) by [@uriyyo](https://github.com/uriyyo) * Switch docs preview and coverage display to use [smokeshow](https://smokeshow.helpmanual.io/) , [#2580](https://github.com/pydantic/pydantic/pull/2580) by [@samuelcolvin](https://github.com/samuelcolvin) * Add `__version__` attribute to pydantic module, [#2572](https://github.com/pydantic/pydantic/pull/2572) by [@paxcodes](https://github.com/paxcodes) * Add `postgresql+asyncpg`, `postgresql+pg8000`, `postgresql+psycopg2`, `postgresql+psycopg2cffi`, `postgresql+py-postgresql` and `postgresql+pygresql` schemes for `PostgresDsn`, [#2567](https://github.com/pydantic/pydantic/pull/2567) by [@postgres-asyncpg](https://github.com/postgres-asyncpg) * Enable the Hypothesis plugin to generate a constrained decimal when the `decimal_places` argument is specified, [#2524](https://github.com/pydantic/pydantic/pull/2524) by [@cwe5590](https://github.com/cwe5590) * Allow `collections.abc.Callable` to be used as type in Python 3.9, [#2519](https://github.com/pydantic/pydantic/pull/2519) by [@daviskirk](https://github.com/daviskirk) * Documentation update how to custom compile pydantic when using pip install, small change in `setup.py` to allow for custom CFLAGS when compiling, [#2517](https://github.com/pydantic/pydantic/pull/2517) by [@peterroelants](https://github.com/peterroelants) * remove side effect of `default_factory` to run it only once even if `Config.validate_all` is set, [#2515](https://github.com/pydantic/pydantic/pull/2515) by [@PrettyWood](https://github.com/PrettyWood) * Add lookahead to ip regexes for `AnyUrl` hosts. This allows urls with DNS labels looking like IPs to validate as they are perfectly valid host names, [#2512](https://github.com/pydantic/pydantic/pull/2512) by [@sbv-csis](https://github.com/sbv-csis) * Set `minItems` and `maxItems` in generated JSON schema for fixed-length tuples, [#2497](https://github.com/pydantic/pydantic/pull/2497) by [@PrettyWood](https://github.com/PrettyWood) * Add `strict` argument to `conbytes`, [#2489](https://github.com/pydantic/pydantic/pull/2489) by [@koxudaxi](https://github.com/koxudaxi) * Support user defined generic field types in generic models, [#2465](https://github.com/pydantic/pydantic/pull/2465) by [@daviskirk](https://github.com/daviskirk) * Add an example and a short explanation of subclassing `GetterDict` to docs, [#2463](https://github.com/pydantic/pydantic/pull/2463) by [@nuno-andre](https://github.com/nuno-andre) * add `KafkaDsn` type, `HttpUrl` now has default port 80 for http and 443 for https, [#2447](https://github.com/pydantic/pydantic/pull/2447) by [@MihanixA](https://github.com/MihanixA) * Add `PastDate` and `FutureDate` types, [#2425](https://github.com/pydantic/pydantic/pull/2425) by [@Kludex](https://github.com/Kludex) * Support generating schema for `Generic` fields with subtypes, [#2375](https://github.com/pydantic/pydantic/pull/2375) by [@maximberg](https://github.com/maximberg) * fix(encoder): serialize `NameEmail` to str, [#2341](https://github.com/pydantic/pydantic/pull/2341) by [@alecgerona](https://github.com/alecgerona) * add `Config.smart_union` to prevent coercion in `Union` if possible, see [the doc](https://docs.pydantic.dev/usage/model_config/#smart-union) for more information, [#2092](https://github.com/pydantic/pydantic/pull/2092) by [@PrettyWood](https://github.com/PrettyWood) * Add ability to use `typing.Counter` as a model field type, [#2060](https://github.com/pydantic/pydantic/pull/2060) by [@uriyyo](https://github.com/uriyyo) * Add parameterised subclasses to `__bases__` when constructing new parameterised classes, so that `A <: B => A[int] <: B[int]`, [#2007](https://github.com/pydantic/pydantic/pull/2007) by [@diabolo-dan](https://github.com/diabolo-dan) * Create `FileUrl` type that allows URLs that conform to [RFC 8089](https://tools.ietf.org/html/rfc8089#section-2) . Add `host_required` parameter, which is `True` by default (`AnyUrl` and subclasses), `False` in `RedisDsn`, `FileUrl`, [#1983](https://github.com/pydantic/pydantic/pull/1983) by [@vgerak](https://github.com/vgerak) * add `confrozenset()`, analogous to `conset()` and `conlist()`, [#1897](https://github.com/pydantic/pydantic/pull/1897) by [@PrettyWood](https://github.com/PrettyWood) * stop calling parent class `root_validator` if overridden, [#1895](https://github.com/pydantic/pydantic/pull/1895) by [@PrettyWood](https://github.com/PrettyWood) * Add `repr` (defaults to `True`) parameter to `Field`, to hide it from the default representation of the `BaseModel`, [#1831](https://github.com/pydantic/pydantic/pull/1831) by [@fnep](https://github.com/fnep) * Accept empty query/fragment URL parts, [#1807](https://github.com/pydantic/pydantic/pull/1807) by [@xavier](https://github.com/xavier) v1.8.2 (2021-05-11)[¶](#v182-2021-05-11 "Permanent link") ---------------------------------------------------------- Warning A security vulnerability, level "moderate" is fixed in v1.8.2. Please upgrade **ASAP**. See security advisory [CVE-2021-29510](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh) * **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](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh) * fix schema generation with Enum by generating a valid name, [#2575](https://github.com/pydantic/pydantic/pull/2575) by [@PrettyWood](https://github.com/PrettyWood) * fix JSON schema generation with a `Literal` of an enum member, [#2536](https://github.com/pydantic/pydantic/pull/2536) by [@PrettyWood](https://github.com/PrettyWood) * Fix bug with configurations declarations that are passed as keyword arguments during class creation, [#2532](https://github.com/pydantic/pydantic/pull/2532) by [@uriyyo](https://github.com/uriyyo) * Allow passing `json_encoders` in class kwargs, [#2521](https://github.com/pydantic/pydantic/pull/2521) by [@layday](https://github.com/layday) * support arbitrary types with custom `__eq__`, [#2483](https://github.com/pydantic/pydantic/pull/2483) by [@PrettyWood](https://github.com/PrettyWood) * support `Annotated` in `validate_arguments` and in generic models with Python 3.9, [#2483](https://github.com/pydantic/pydantic/pull/2483) by [@PrettyWood](https://github.com/PrettyWood) v1.8.1 (2021-03-03)[¶](#v181-2021-03-03 "Permanent link") ---------------------------------------------------------- Bug fixes for regressions and new features from `v1.8` * allow elements of `Config.field` to update elements of a `Field`, [#2461](https://github.com/pydantic/pydantic/pull/2461) by [@samuelcolvin](https://github.com/samuelcolvin) * fix validation with a `BaseModel` field and a custom root type, [#2449](https://github.com/pydantic/pydantic/pull/2449) by [@PrettyWood](https://github.com/PrettyWood) * expose `Pattern` encoder to `fastapi`, [#2444](https://github.com/pydantic/pydantic/pull/2444) by [@PrettyWood](https://github.com/PrettyWood) * enable the Hypothesis plugin to generate a constrained float when the `multiple_of` argument is specified, [#2442](https://github.com/pydantic/pydantic/pull/2442) by [@tobi-lipede-oodle](https://github.com/tobi-lipede-oodle) * Avoid `RecursionError` when using some types like `Enum` or `Literal` with generic models, [#2436](https://github.com/pydantic/pydantic/pull/2436) by [@PrettyWood](https://github.com/PrettyWood) * do not overwrite declared `__hash__` in subclasses of a model, [#2422](https://github.com/pydantic/pydantic/pull/2422) by [@PrettyWood](https://github.com/PrettyWood) * fix `mypy` complaints on `Path` and `UUID` related custom types, [#2418](https://github.com/pydantic/pydantic/pull/2418) by [@PrettyWood](https://github.com/PrettyWood) * Support properly variable length tuples of compound types, [#2416](https://github.com/pydantic/pydantic/pull/2416) by [@PrettyWood](https://github.com/PrettyWood) v1.8 (2021-02-26)[¶](#v18-2021-02-26 "Permanent link") ------------------------------------------------------- Thank you to pydantic's sponsors: [@jorgecarleitao](https://github.com/jorgecarleitao) , [@BCarley](https://github.com/BCarley) , [@chdsbd](https://github.com/chdsbd) , [@tiangolo](https://github.com/tiangolo) , [@matin](https://github.com/matin) , [@linusg](https://github.com/linusg) , [@kevinalh](https://github.com/kevinalh) , [@koxudaxi](https://github.com/koxudaxi) , [@timdrijvers](https://github.com/timdrijvers) , [@mkeen](https://github.com/mkeen) , [@meadsteve](https://github.com/meadsteve) , [@ginomempin](https://github.com/ginomempin) , [@primer-io](https://github.com/primer-io) , [@and-semakin](https://github.com/and-semakin) , [@tomthorogood](https://github.com/tomthorogood) , [@AjitZK](https://github.com/AjitZK) , [@westonsteimel](https://github.com/westonsteimel) , [@Mazyod](https://github.com/Mazyod) , [@christippett](https://github.com/christippett) , [@CarlosDomingues](https://github.com/CarlosDomingues) , [@Kludex](https://github.com/Kludex) , [@r-m-n](https://github.com/r-m-n) for their kind support. ### Highlights[¶](#highlights_1 "Permanent link") * [Hypothesis plugin](https://docs.pydantic.dev/hypothesis_plugin/) for testing, [#2097](https://github.com/pydantic/pydantic/pull/2097) by [@Zac-HD](https://github.com/Zac-HD) * support for [`NamedTuple` and `TypedDict`](https://docs.pydantic.dev/usage/types/#annotated-types) , [#2216](https://github.com/pydantic/pydantic/pull/2216) by [@PrettyWood](https://github.com/PrettyWood) * Support [`Annotated` hints on model fields](https://docs.pydantic.dev/usage/schema/#typingannotated-fields) , [#2147](https://github.com/pydantic/pydantic/pull/2147) by [@JacobHayes](https://github.com/JacobHayes) * [`frozen` parameter on `Config`](https://docs.pydantic.dev/usage/model_config/) to allow models to be hashed, [#1880](https://github.com/pydantic/pydantic/pull/1880) by [@rhuille](https://github.com/rhuille) ### Changes[¶](#changes_10 "Permanent link") * **Breaking Change**, remove old deprecation aliases from v1, [#2415](https://github.com/pydantic/pydantic/pull/2415) by [@samuelcolvin](https://github.com/samuelcolvin) : * remove notes on migrating to v1 in docs * remove `Schema` which was replaced by `Field` * remove `Config.case_insensitive` which was replaced by `Config.case_sensitive` (default `False`) * remove `Config.allow_population_by_alias` which was replaced by `Config.allow_population_by_field_name` * remove `model.fields` which was replaced by `model.__fields__` * remove `model.to_string()` which was replaced by `str(model)` * remove `model.__values__` which was replaced by `model.__dict__` * **Breaking Change:** always validate only first sublevel items with `each_item`. There were indeed some edge cases with some compound types where the validated items were the last sublevel ones, [#1933](https://github.com/pydantic/pydantic/pull/1933) by [@PrettyWood](https://github.com/PrettyWood) * Update docs extensions to fix local syntax highlighting, [#2400](https://github.com/pydantic/pydantic/pull/2400) by [@daviskirk](https://github.com/daviskirk) * fix: allow `utils.lenient_issubclass` to handle `typing.GenericAlias` objects like `list[str]` in Python >= 3.9, [#2399](https://github.com/pydantic/pydantic/pull/2399) by [@daviskirk](https://github.com/daviskirk) * Improve field declaration for _pydantic_ `dataclass` by allowing the usage of _pydantic_ `Field` or `'metadata'` kwarg of `dataclasses.field`, [#2384](https://github.com/pydantic/pydantic/pull/2384) by [@PrettyWood](https://github.com/PrettyWood) * Making `typing-extensions` a required dependency, [#2368](https://github.com/pydantic/pydantic/pull/2368) by [@samuelcolvin](https://github.com/samuelcolvin) * Make `resolve_annotations` more lenient, allowing for missing modules, [#2363](https://github.com/pydantic/pydantic/pull/2363) by [@samuelcolvin](https://github.com/samuelcolvin) * Allow configuring models through class kwargs, [#2356](https://github.com/pydantic/pydantic/pull/2356) by [@Bobronium](https://github.com/Bobronium) * Prevent `Mapping` subclasses from always being coerced to `dict`, [#2325](https://github.com/pydantic/pydantic/pull/2325) by [@ofek](https://github.com/ofek) * fix: allow `None` for type `Optional[conset / conlist]`, [#2320](https://github.com/pydantic/pydantic/pull/2320) by [@PrettyWood](https://github.com/PrettyWood) * Support empty tuple type, [#2318](https://github.com/pydantic/pydantic/pull/2318) by [@PrettyWood](https://github.com/PrettyWood) * fix: `python_requires` metadata to require >=3.6.1, [#2306](https://github.com/pydantic/pydantic/pull/2306) by [@hukkinj1](https://github.com/hukkinj1) * Properly encode `Decimal` with, or without any decimal places, [#2293](https://github.com/pydantic/pydantic/pull/2293) by [@hultner](https://github.com/hultner) * fix: update `__fields_set__` in `BaseModel.copy(update=…)`, [#2290](https://github.com/pydantic/pydantic/pull/2290) by [@PrettyWood](https://github.com/PrettyWood) * fix: keep order of fields with `BaseModel.construct()`, [#2281](https://github.com/pydantic/pydantic/pull/2281) by [@PrettyWood](https://github.com/PrettyWood) * Support generating schema for Generic fields, [#2262](https://github.com/pydantic/pydantic/pull/2262) by [@maximberg](https://github.com/maximberg) * Fix `validate_decorator` so `**kwargs` doesn't exclude values when the keyword has the same name as the `*args` or `**kwargs` names, [#2251](https://github.com/pydantic/pydantic/pull/2251) by [@cybojenix](https://github.com/cybojenix) * Prevent overriding positional arguments with keyword arguments in `validate_arguments`, as per behaviour with native functions, [#2249](https://github.com/pydantic/pydantic/pull/2249) by [@cybojenix](https://github.com/cybojenix) * add documentation for `con*` type functions, [#2242](https://github.com/pydantic/pydantic/pull/2242) by [@tayoogunbiyi](https://github.com/tayoogunbiyi) * Support custom root type (aka `__root__`) when using `parse_obj()` with nested models, [#2238](https://github.com/pydantic/pydantic/pull/2238) by [@PrettyWood](https://github.com/PrettyWood) * Support custom root type (aka `__root__`) with `from_orm()`, [#2237](https://github.com/pydantic/pydantic/pull/2237) by [@PrettyWood](https://github.com/PrettyWood) * ensure cythonized functions are left untouched when creating models, based on [#1944](https://github.com/pydantic/pydantic/pull/1944) by [@kollmats](https://github.com/kollmats) , [#2228](https://github.com/pydantic/pydantic/pull/2228) by [@samuelcolvin](https://github.com/samuelcolvin) * Resolve forward refs for stdlib dataclasses converted into _pydantic_ ones, [#2220](https://github.com/pydantic/pydantic/pull/2220) by [@PrettyWood](https://github.com/PrettyWood) * Add support for `NamedTuple` 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](https://github.com/pydantic/pydantic/pull/2216) by [@PrettyWood](https://github.com/PrettyWood) * Do not ignore annotated fields when type is `Union[Type[...], ...]`, [#2213](https://github.com/pydantic/pydantic/pull/2213) by [@PrettyWood](https://github.com/PrettyWood) * Raise a user-friendly `TypeError` when a `root_validator` does not return a `dict` (e.g. `None`), [#2209](https://github.com/pydantic/pydantic/pull/2209) by [@masalim2](https://github.com/masalim2) * Add a `FrozenSet[str]` type annotation to the `allowed_schemes` argument on the `strict_url` field type, [#2198](https://github.com/pydantic/pydantic/pull/2198) by [@Midnighter](https://github.com/Midnighter) * add `allow_mutation` constraint to `Field`, [#2195](https://github.com/pydantic/pydantic/pull/2195) by [@sblack-usu](https://github.com/sblack-usu) * Allow `Field` with a `default_factory` to be used as an argument to a function decorated with `validate_arguments`, [#2176](https://github.com/pydantic/pydantic/pull/2176) by [@thomascobb](https://github.com/thomascobb) * Allow non-existent secrets directory by only issuing a warning, [#2175](https://github.com/pydantic/pydantic/pull/2175) by [@davidolrik](https://github.com/davidolrik) * fix URL regex to parse fragment without query string, [#2168](https://github.com/pydantic/pydantic/pull/2168) by [@andrewmwhite](https://github.com/andrewmwhite) * fix: ensure to always return one of the values in `Literal` field type, [#2166](https://github.com/pydantic/pydantic/pull/2166) by [@PrettyWood](https://github.com/PrettyWood) * Support `typing.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](https://github.com/pydantic/pydantic/pull/2147)\ by [@JacobHayes](https://github.com/JacobHayes)\ \ * Added `StrictBytes` type as well as `strict=False` option to `ConstrainedBytes`, [#2136](https://github.com/pydantic/pydantic/pull/2136)\ by [@rlizzo](https://github.com/rlizzo)\ \ * added `Config.anystr_lower` and `to_lower` kwarg to `constr` and `conbytes`, [#2134](https://github.com/pydantic/pydantic/pull/2134)\ by [@tayoogunbiyi](https://github.com/tayoogunbiyi)\ \ * Support plain `typing.Tuple` type, [#2132](https://github.com/pydantic/pydantic/pull/2132)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Add a bound method `validate` to functions decorated with `validate_arguments` to validate parameters without actually calling the function, [#2127](https://github.com/pydantic/pydantic/pull/2127)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Add the ability to customize settings sources (add / disable / change priority order), [#2107](https://github.com/pydantic/pydantic/pull/2107)\ by [@kozlek](https://github.com/kozlek)\ \ * Fix mypy complaints about most custom _pydantic_ types, [#2098](https://github.com/pydantic/pydantic/pull/2098)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Add a [Hypothesis](https://hypothesis.readthedocs.io/)\ plugin for easier [property-based testing](https://increment.com/testing/in-praise-of-property-based-testing/)\ with Pydantic's custom types - [usage details here](https://docs.pydantic.dev/hypothesis_plugin/)\ , [#2097](https://github.com/pydantic/pydantic/pull/2097)\ by [@Zac-HD](https://github.com/Zac-HD)\ \ * add validator for `None`, `NoneType` or `Literal[None]`, [#2095](https://github.com/pydantic/pydantic/pull/2095)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Handle properly fields of type `Callable` with a default value, [#2094](https://github.com/pydantic/pydantic/pull/2094)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Updated `create_model` return type annotation to return type which inherits from `__base__` argument, [#2071](https://github.com/pydantic/pydantic/pull/2071)\ by [@uriyyo](https://github.com/uriyyo)\ \ * Add merged `json_encoders` inheritance, [#2064](https://github.com/pydantic/pydantic/pull/2064)\ by [@art049](https://github.com/art049)\ \ * allow overwriting `ClassVar`s in sub-models without having to re-annotate them, [#2061](https://github.com/pydantic/pydantic/pull/2061)\ by [@layday](https://github.com/layday)\ \ * add default encoder for `Pattern` type, [#2045](https://github.com/pydantic/pydantic/pull/2045)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Add `NonNegativeInt`, `NonPositiveInt`, `NonNegativeFloat`, `NonPositiveFloat`, [#1975](https://github.com/pydantic/pydantic/pull/1975)\ by [@mdavis-xyz](https://github.com/mdavis-xyz)\ \ * Use % for percentage in string format of colors, [#1960](https://github.com/pydantic/pydantic/pull/1960)\ by [@EdwardBetts](https://github.com/EdwardBetts)\ \ * Fixed issue causing `KeyError` to be raised when building schema from multiple `BaseModel` with the same names declared in separate classes, [#1912](https://github.com/pydantic/pydantic/pull/1912)\ by [@JSextonn](https://github.com/JSextonn)\ \ * Add `rediss` (Redis over SSL) protocol to `RedisDsn` Allow URLs without `user` part (e.g., `rediss://:pass@localhost`), [#1911](https://github.com/pydantic/pydantic/pull/1911)\ by [@TrDex](https://github.com/TrDex)\ \ * Add a new `frozen` 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](https://github.com/pydantic/pydantic/pull/1880)\ by [@rhuille](https://github.com/rhuille)\ \ * fix schema generation with multiple Enums having the same name, [#1857](https://github.com/pydantic/pydantic/pull/1857)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Added support for 13/19 digits VISA credit cards in `PaymentCardNumber` type, [#1416](https://github.com/pydantic/pydantic/pull/1416)\ by [@AlexanderSov](https://github.com/AlexanderSov)\ \ * fix: prevent `RecursionError` while using recursive `GenericModel`s, [#1370](https://github.com/pydantic/pydantic/pull/1370)\ by [@xppt](https://github.com/xppt)\ \ * use `enum` for `typing.Literal` in JSON schema, [#1350](https://github.com/pydantic/pydantic/pull/1350)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Fix: some recursive models did not require `update_forward_refs` and silently behaved incorrectly, [#1201](https://github.com/pydantic/pydantic/pull/1201)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Fix bug where generic models with fields where the typevar is nested in another type `a: List[T]` are considered to be concrete. This allows these models to be subclassed and composed as expected, [#947](https://github.com/pydantic/pydantic/pull/947)\ by [@daviskirk](https://github.com/daviskirk)\ \ * Add `Config.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](https://github.com/pydantic/pydantic/pull/265)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.7.4 (2021-05-11)[¶](#v174-2021-05-11 "Permanent link")\ \ ----------------------------------------------------------\ \ * **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](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh)\ \ \ v1.7.3 (2020-11-30)[¶](#v173-2020-11-30 "Permanent link")\ \ ----------------------------------------------------------\ \ Thank you to pydantic's sponsors: [@timdrijvers](https://github.com/timdrijvers)\ , [@BCarley](https://github.com/BCarley)\ , [@chdsbd](https://github.com/chdsbd)\ , [@tiangolo](https://github.com/tiangolo)\ , [@matin](https://github.com/matin)\ , [@linusg](https://github.com/linusg)\ , [@kevinalh](https://github.com/kevinalh)\ , [@jorgecarleitao](https://github.com/jorgecarleitao)\ , [@koxudaxi](https://github.com/koxudaxi)\ , [@primer-api](https://github.com/primer-api)\ , [@mkeen](https://github.com/mkeen)\ , [@meadsteve](https://github.com/meadsteve)\ for their kind support.\ \ * fix: set right default value for required (optional) fields, [#2142](https://github.com/pydantic/pydantic/pull/2142)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * fix: support `underscore_attrs_are_private` with generic models, [#2138](https://github.com/pydantic/pydantic/pull/2138)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * fix: update all modified field values in `root_validator` when `validate_assignment` is on, [#2116](https://github.com/pydantic/pydantic/pull/2116)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Allow pickling of `pydantic.dataclasses.dataclass` dynamically created from a built-in `dataclasses.dataclass`, [#2111](https://github.com/pydantic/pydantic/pull/2111)\ by [@aimestereo](https://github.com/aimestereo)\ \ * Fix a regression where Enum fields would not propagate keyword arguments to the schema, [#2109](https://github.com/pydantic/pydantic/pull/2109)\ by [@bm424](https://github.com/bm424)\ \ * Ignore `__doc__` as private attribute when `Config.underscore_attrs_are_private` is set, [#2090](https://github.com/pydantic/pydantic/pull/2090)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.7.2 (2020-11-01)[¶](#v172-2020-11-01 "Permanent link")\ \ ----------------------------------------------------------\ \ * fix slow `GenericModel` concrete model creation, allow `GenericModel` concrete name reusing in module, [#2078](https://github.com/pydantic/pydantic/pull/2078)\ by [@Bobronium](https://github.com/Bobronium)\ \ * keep the order of the fields when `validate_assignment` is set, [#2073](https://github.com/pydantic/pydantic/pull/2073)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * forward all the params of the stdlib `dataclass` when converted into _pydantic_ `dataclass`, [#2065](https://github.com/pydantic/pydantic/pull/2065)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.7.1 (2020-10-28)[¶](#v171-2020-10-28 "Permanent link")\ \ ----------------------------------------------------------\ \ Thank you to pydantic's sponsors: [@timdrijvers](https://github.com/timdrijvers)\ , [@BCarley](https://github.com/BCarley)\ , [@chdsbd](https://github.com/chdsbd)\ , [@tiangolo](https://github.com/tiangolo)\ , [@matin](https://github.com/matin)\ , [@linusg](https://github.com/linusg)\ , [@kevinalh](https://github.com/kevinalh)\ , [@jorgecarleitao](https://github.com/jorgecarleitao)\ , [@koxudaxi](https://github.com/koxudaxi)\ , [@primer-api](https://github.com/primer-api)\ , [@mkeen](https://github.com/mkeen)\ for their kind support.\ \ * fix annotation of `validate_arguments` when passing configuration as argument, [#2055](https://github.com/pydantic/pydantic/pull/2055)\ by [@layday](https://github.com/layday)\ \ * Fix mypy assignment error when using `PrivateAttr`, [#2048](https://github.com/pydantic/pydantic/pull/2048)\ by [@aphedges](https://github.com/aphedges)\ \ * fix `underscore_attrs_are_private` causing `TypeError` when overriding `__init__`, [#2047](https://github.com/pydantic/pydantic/pull/2047)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fixed regression introduced in v1.7 involving exception handling in field validators when `validate_assignment=True`, [#2044](https://github.com/pydantic/pydantic/pull/2044)\ by [@johnsabath](https://github.com/johnsabath)\ \ * fix: _pydantic_ `dataclass` can inherit from stdlib `dataclass` and `Config.arbitrary_types_allowed` is supported, [#2042](https://github.com/pydantic/pydantic/pull/2042)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.7 (2020-10-26)[¶](#v17-2020-10-26 "Permanent link")\ \ -------------------------------------------------------\ \ Thank you to pydantic's sponsors: [@timdrijvers](https://github.com/timdrijvers)\ , [@BCarley](https://github.com/BCarley)\ , [@chdsbd](https://github.com/chdsbd)\ , [@tiangolo](https://github.com/tiangolo)\ , [@matin](https://github.com/matin)\ , [@linusg](https://github.com/linusg)\ , [@kevinalh](https://github.com/kevinalh)\ , [@jorgecarleitao](https://github.com/jorgecarleitao)\ , [@koxudaxi](https://github.com/koxudaxi)\ , [@primer-api](https://github.com/primer-api)\ for their kind support.\ \ ### Highlights[¶](#highlights_2 "Permanent link")\ \ * Python 3.9 support, thanks [@PrettyWood](https://github.com/PrettyWood)\ \ * [Private model attributes](https://docs.pydantic.dev/usage/models/#private-model-attributes)\ , thanks [@Bobronium](https://github.com/Bobronium)\ \ * ["secrets files" support in `BaseSettings`](https://docs.pydantic.dev/usage/settings/#secret-support)\ , thanks [@mdgilene](https://github.com/mdgilene)\ \ * [convert stdlib dataclasses to pydantic dataclasses and use stdlib dataclasses in models](https://docs.pydantic.dev/usage/dataclasses/#stdlib-dataclasses-and-pydantic-dataclasses)\ , thanks [@PrettyWood](https://github.com/PrettyWood)\ \ \ ### Changes[¶](#changes_11 "Permanent link")\ \ * **Breaking Change:** remove `__field_defaults__`, add `default_factory` support with `BaseModel.construct`. Use `.get_default()` method on fields in `__fields__` attribute instead, [#1732](https://github.com/pydantic/pydantic/pull/1732)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Rearrange CI to run linting as a separate job, split install recipes for different tasks, [#2020](https://github.com/pydantic/pydantic/pull/2020)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Allows subclasses of generic models to make some, or all, of the superclass's type parameters concrete, while also defining new type parameters in the subclass, [#2005](https://github.com/pydantic/pydantic/pull/2005)\ by [@choogeboom](https://github.com/choogeboom)\ \ * Call validator with the correct `values` parameter type in `BaseModel.__setattr__`, when `validate_assignment = True` in model config, [#1999](https://github.com/pydantic/pydantic/pull/1999)\ by [@me-ransh](https://github.com/me-ransh)\ \ * Force `fields.Undefined` to be a singleton object, fixing inherited generic model schemas, [#1981](https://github.com/pydantic/pydantic/pull/1981)\ by [@daviskirk](https://github.com/daviskirk)\ \ * Include tests in source distributions, [#1976](https://github.com/pydantic/pydantic/pull/1976)\ by [@sbraz](https://github.com/sbraz)\ \ * Add ability to use `min_length/max_length` constraints with secret types, [#1974](https://github.com/pydantic/pydantic/pull/1974)\ by [@uriyyo](https://github.com/uriyyo)\ \ * Also check `root_validators` when `validate_assignment` is on, [#1971](https://github.com/pydantic/pydantic/pull/1971)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Fix const validators not running when custom validators are present, [#1957](https://github.com/pydantic/pydantic/pull/1957)\ by [@hmvp](https://github.com/hmvp)\ \ * add `deque` to field types, [#1935](https://github.com/pydantic/pydantic/pull/1935)\ by [@wozniakty](https://github.com/wozniakty)\ \ * add basic support for Python 3.9, [#1832](https://github.com/pydantic/pydantic/pull/1832)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Fix typo in the anchor of exporting\_models.md#modelcopy and incorrect description, [#1821](https://github.com/pydantic/pydantic/pull/1821)\ by [@KimMachineGun](https://github.com/KimMachineGun)\ \ * Added ability for `BaseSettings` to read "secret files", [#1820](https://github.com/pydantic/pydantic/pull/1820)\ by [@mdgilene](https://github.com/mdgilene)\ \ * add `parse_raw_as` utility function, [#1812](https://github.com/pydantic/pydantic/pull/1812)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Support home directory relative paths for `dotenv` files (e.g. `~/.env`), [#1803](https://github.com/pydantic/pydantic/pull/1803)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Clarify documentation for `parse_file` to show that the argument should be a file _path_ not a file-like object, [#1794](https://github.com/pydantic/pydantic/pull/1794)\ by [@mdavis-xyz](https://github.com/mdavis-xyz)\ \ * Fix false positive from mypy plugin when a class nested within a `BaseModel` is named `Model`, [#1770](https://github.com/pydantic/pydantic/pull/1770)\ by [@selimb](https://github.com/selimb)\ \ * add basic support of Pattern type in schema generation, [#1767](https://github.com/pydantic/pydantic/pull/1767)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Support custom title, description and default in schema of enums, [#1748](https://github.com/pydantic/pydantic/pull/1748)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Properly represent `Literal` Enums when `use_enum_values` is True, [#1747](https://github.com/pydantic/pydantic/pull/1747)\ by [@noelevans](https://github.com/noelevans)\ \ * Allows timezone information to be added to strings to be formatted as time objects. Permitted formats are `Z` for UTC or an offset for absolute positive or negative time shifts. Or the timezone data can be omitted, [#1744](https://github.com/pydantic/pydantic/pull/1744)\ by [@noelevans](https://github.com/noelevans)\ \ * Add stub `__init__` with Python 3.6 signature for `ForwardRef`, [#1738](https://github.com/pydantic/pydantic/pull/1738)\ by [@sirtelemak](https://github.com/sirtelemak)\ \ * Fix behaviour with forward refs and optional fields in nested models, [#1736](https://github.com/pydantic/pydantic/pull/1736)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * add `Enum` and `IntEnum` as valid types for fields, [#1735](https://github.com/pydantic/pydantic/pull/1735)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Change default value of `__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](https://github.com/pydantic/pydantic/pull/1686)\ by [@Bobronium](https://github.com/Bobronium)\ \ * Add private attributes support, [#1679](https://github.com/pydantic/pydantic/pull/1679)\ by [@Bobronium](https://github.com/Bobronium)\ \ * add `config` to `@validate_arguments`, [#1663](https://github.com/pydantic/pydantic/pull/1663)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Allow descendant Settings models to override env variable names for the fields defined in parent Settings models with `env` in their `Config`. Previously only `env_prefix` configuration option was applicable, [#1561](https://github.com/pydantic/pydantic/pull/1561)\ by [@ojomio](https://github.com/ojomio)\ \ * Support `ref_template` when creating schema `$ref`s, [#1479](https://github.com/pydantic/pydantic/pull/1479)\ by [@kilo59](https://github.com/kilo59)\ \ * Add a `__call__` stub to `PyObject` so that mypy will know that it is callable, [#1352](https://github.com/pydantic/pydantic/pull/1352)\ by [@brianmaissy](https://github.com/brianmaissy)\ \ * `pydantic.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](https://github.com/pydantic/pydantic/pull/744)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.6.2 (2021-05-11)[¶](#v162-2021-05-11 "Permanent link")\ \ ----------------------------------------------------------\ \ * **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](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh)\ \ \ v1.6.1 (2020-07-15)[¶](#v161-2020-07-15 "Permanent link")\ \ ----------------------------------------------------------\ \ * fix validation and parsing of nested models with `default_factory`, [#1710](https://github.com/pydantic/pydantic/pull/1710)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ \ v1.6 (2020-07-11)[¶](#v16-2020-07-11 "Permanent link")\ \ -------------------------------------------------------\ \ Thank you to pydantic's sponsors: [@matin](https://github.com/matin)\ , [@tiangolo](https://github.com/tiangolo)\ , [@chdsbd](https://github.com/chdsbd)\ , [@jorgecarleitao](https://github.com/jorgecarleitao)\ , and 1 anonymous sponsor for their kind support.\ \ * Modify validators for `conlist` and `conset` to not have `always=True`, [#1682](https://github.com/pydantic/pydantic/pull/1682)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add port check to `AnyUrl` (can't exceed 65536) ports are 16 insigned bits: `0 <= port <= 2**16-1` src: [rfc793 header format](https://tools.ietf.org/html/rfc793#section-3.1)\ , [#1654](https://github.com/pydantic/pydantic/pull/1654)\ by [@flapili](https://github.com/flapili)\ \ * Document default `regex` anchoring semantics, [#1648](https://github.com/pydantic/pydantic/pull/1648)\ by [@yurikhan](https://github.com/yurikhan)\ \ * Use `chain.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](https://github.com/pydantic/pydantic/pull/1642)\ by [@cool-RR](https://github.com/cool-RR)\ \ * Add `conset()`, analogous to `conlist()`, [#1623](https://github.com/pydantic/pydantic/pull/1623)\ by [@patrickkwang](https://github.com/patrickkwang)\ \ * make Pydantic errors (un)pickable, [#1616](https://github.com/pydantic/pydantic/pull/1616)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Allow custom encoding for `dotenv` files, [#1615](https://github.com/pydantic/pydantic/pull/1615)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Ensure `SchemaExtraCallable` is always defined to get type hints on BaseConfig, [#1614](https://github.com/pydantic/pydantic/pull/1614)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Update datetime parser to support negative timestamps, [#1600](https://github.com/pydantic/pydantic/pull/1600)\ by [@mlbiche](https://github.com/mlbiche)\ \ * Update mypy, remove `AnyType` alias for `Type[Any]`, [#1598](https://github.com/pydantic/pydantic/pull/1598)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Adjust handling of root validators so that errors are aggregated from _all_ failing root validators, instead of reporting on only the first root validator to fail, [#1586](https://github.com/pydantic/pydantic/pull/1586)\ by [@beezee](https://github.com/beezee)\ \ * Make `__modify_schema__` on Enums apply to the enum schema rather than fields that use the enum, [#1581](https://github.com/pydantic/pydantic/pull/1581)\ by [@therefromhere](https://github.com/therefromhere)\ \ * Fix behavior of `__all__` key when used in conjunction with index keys in advanced include/exclude of fields that are sequences, [#1579](https://github.com/pydantic/pydantic/pull/1579)\ by [@xspirus](https://github.com/xspirus)\ \ * Subclass validators do not run when referencing a `List` field defined in a parent class when `each_item=True`. Added an example to the docs illustrating this, [#1566](https://github.com/pydantic/pydantic/pull/1566)\ by [@samueldeklund](https://github.com/samueldeklund)\ \ * change `schema.field_class_to_schema` to support `frozenset` in schema, [#1557](https://github.com/pydantic/pydantic/pull/1557)\ by [@wangpeibao](https://github.com/wangpeibao)\ \ * Call `__modify_schema__` only for the field schema, [#1552](https://github.com/pydantic/pydantic/pull/1552)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Move the assignment of `field.validate_always` in `fields.py` so the `always` parameter of validators work on inheritance, [#1545](https://github.com/pydantic/pydantic/pull/1545)\ by [@dcHHH](https://github.com/dcHHH)\ \ * Added support for UUID instantiation through 16 byte strings such as `b'\x12\x34\x56\x78' * 4`. This was done to support `BINARY(16)` columns in sqlalchemy, [#1541](https://github.com/pydantic/pydantic/pull/1541)\ by [@shawnwall](https://github.com/shawnwall)\ \ * Add a test assertion that `default_factory` can return a singleton, [#1523](https://github.com/pydantic/pydantic/pull/1523)\ by [@therefromhere](https://github.com/therefromhere)\ \ * Add `NameEmail.__eq__` so duplicate `NameEmail` instances are evaluated as equal, [#1514](https://github.com/pydantic/pydantic/pull/1514)\ by [@stephen-bunn](https://github.com/stephen-bunn)\ \ * Add datamodel-code-generator link in pydantic document site, [#1500](https://github.com/pydantic/pydantic/pull/1500)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * Added a "Discussion of Pydantic" section to the documentation, with a link to "Pydantic Introduction" video by Alexander Hultnér, [#1499](https://github.com/pydantic/pydantic/pull/1499)\ by [@hultner](https://github.com/hultner)\ \ * Avoid some side effects of `default_factory` by calling it only once if possible and by not setting a default value in the schema, [#1491](https://github.com/pydantic/pydantic/pull/1491)\ by [@PrettyWood](https://github.com/PrettyWood)\ \ * Added docs about dumping dataclasses to JSON, [#1487](https://github.com/pydantic/pydantic/pull/1487)\ by [@mikegrima](https://github.com/mikegrima)\ \ * Make `BaseModel.__signature__` class-only, so getting `__signature__` from model instance will raise `AttributeError`, [#1466](https://github.com/pydantic/pydantic/pull/1466)\ by [@Bobronium](https://github.com/Bobronium)\ \ * include `'format': 'password'` in the schema for secret types, [#1424](https://github.com/pydantic/pydantic/pull/1424)\ by [@atheuz](https://github.com/atheuz)\ \ * Modify schema constraints on `ConstrainedFloat` 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](https://github.com/pydantic/pydantic/pull/1417)\ by [@vdwees](https://github.com/vdwees)\ \ * Squash internal `__root__` dicts in `.dict()` (and, by extension, in `.json()`), [#1414](https://github.com/pydantic/pydantic/pull/1414)\ by [@patrickkwang](https://github.com/patrickkwang)\ \ * Move `const` validator to post-validators so it validates the parsed value, [#1410](https://github.com/pydantic/pydantic/pull/1410)\ by [@selimb](https://github.com/selimb)\ \ * Fix model validation to handle nested literals, e.g. `Literal['foo', Literal['bar']]`, [#1364](https://github.com/pydantic/pydantic/pull/1364)\ by [@DBCerigo](https://github.com/DBCerigo)\ \ * Remove `user_required = True` from `RedisDsn`, neither user nor password are required, [#1275](https://github.com/pydantic/pydantic/pull/1275)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Remove extra `allOf` from schema for fields with `Union` and custom `Field`, [#1209](https://github.com/pydantic/pydantic/pull/1209)\ by [@mostaphaRoudsari](https://github.com/mostaphaRoudsari)\ \ * Updates OpenAPI schema generation to output all enums as separate models. Instead of inlining the enum values in the model schema, models now use a `$ref` property to point to the enum definition, [#1173](https://github.com/pydantic/pydantic/pull/1173)\ by [@calvinwyoung](https://github.com/calvinwyoung)\ \ \ v1.5.1 (2020-04-23)[¶](#v151-2020-04-23 "Permanent link")\ \ ----------------------------------------------------------\ \ * Signature generation with `extra: allow` never uses a field name, [#1418](https://github.com/pydantic/pydantic/pull/1418)\ by [@prettywood](https://github.com/prettywood)\ \ * Avoid mutating `Field` default value, [#1412](https://github.com/pydantic/pydantic/pull/1412)\ by [@prettywood](https://github.com/prettywood)\ \ \ v1.5 (2020-04-18)[¶](#v15-2020-04-18 "Permanent link")\ \ -------------------------------------------------------\ \ * Make includes/excludes arguments for `.dict()`, `._iter()`, ..., immutable, [#1404](https://github.com/pydantic/pydantic/pull/1404)\ by [@AlexECX](https://github.com/AlexECX)\ \ * Always use a field's real name with includes/excludes in `model._iter()`, regardless of `by_alias`, [#1397](https://github.com/pydantic/pydantic/pull/1397)\ by [@AlexECX](https://github.com/AlexECX)\ \ * Update constr regex example to include start and end lines, [#1396](https://github.com/pydantic/pydantic/pull/1396)\ by [@lmcnearney](https://github.com/lmcnearney)\ \ * Confirm that shallow `model.copy()` does make a shallow copy of attributes, [#1383](https://github.com/pydantic/pydantic/pull/1383)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Renaming `model_name` argument of `main.create_model()` to `__model_name` to allow using `model_name` as a field name, [#1367](https://github.com/pydantic/pydantic/pull/1367)\ by [@kittipatv](https://github.com/kittipatv)\ \ * Replace raising of exception to silent passing for non-Var attributes in mypy plugin, [#1345](https://github.com/pydantic/pydantic/pull/1345)\ by [@b0g3r](https://github.com/b0g3r)\ \ * Remove `typing_extensions` dependency for Python 3.8, [#1342](https://github.com/pydantic/pydantic/pull/1342)\ by [@prettywood](https://github.com/prettywood)\ \ * Make `SecretStr` and `SecretBytes` initialization idempotent, [#1330](https://github.com/pydantic/pydantic/pull/1330)\ by [@atheuz](https://github.com/atheuz)\ \ * document making secret types dumpable using the json method, [#1328](https://github.com/pydantic/pydantic/pull/1328)\ by [@atheuz](https://github.com/atheuz)\ \ * Move all testing and build to github actions, add windows and macos binaries, thank you [@StephenBrown2](https://github.com/StephenBrown2)\ for much help, [#1326](https://github.com/pydantic/pydantic/pull/1326)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix card number length check in `PaymentCardNumber`, `PaymentCardBrand` now inherits from `str`, [#1317](https://github.com/pydantic/pydantic/pull/1317)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Have `BaseModel` inherit from `Representation` to make mypy happy when overriding `__str__`, [#1310](https://github.com/pydantic/pydantic/pull/1310)\ by [@FuegoFro](https://github.com/FuegoFro)\ \ * Allow `None` as input to all optional list fields, [#1307](https://github.com/pydantic/pydantic/pull/1307)\ by [@prettywood](https://github.com/prettywood)\ \ * Add `datetime` field to `default_factory` example, [#1301](https://github.com/pydantic/pydantic/pull/1301)\ by [@StephenBrown2](https://github.com/StephenBrown2)\ \ * Allow subclasses of known types to be encoded with superclass encoder, [#1291](https://github.com/pydantic/pydantic/pull/1291)\ by [@StephenBrown2](https://github.com/StephenBrown2)\ \ * Exclude exported fields from all elements of a list/tuple of submodels/dicts with `'__all__'`, [#1286](https://github.com/pydantic/pydantic/pull/1286)\ by [@masalim2](https://github.com/masalim2)\ \ * Add pydantic.color.Color objects as available input for Color fields, [#1258](https://github.com/pydantic/pydantic/pull/1258)\ by [@leosussan](https://github.com/leosussan)\ \ * In examples, type nullable fields as `Optional`, so that these are valid mypy annotations, [#1248](https://github.com/pydantic/pydantic/pull/1248)\ by [@kokes](https://github.com/kokes)\ \ * Make `pattern_validator()` accept pre-compiled `Pattern` objects. Fix `str_validator()` return type to `str`, [#1237](https://github.com/pydantic/pydantic/pull/1237)\ by [@adamgreg](https://github.com/adamgreg)\ \ * Document how to manage Generics and inheritance, [#1229](https://github.com/pydantic/pydantic/pull/1229)\ by [@esadruhn](https://github.com/esadruhn)\ \ * `update_forward_refs()` method of BaseModel now copies `__dict__` of class module instead of modifying it, [#1228](https://github.com/pydantic/pydantic/pull/1228)\ by [@paul-ilyin](https://github.com/paul-ilyin)\ \ * Support instance methods and class methods with `@validate_arguments`, [#1222](https://github.com/pydantic/pydantic/pull/1222)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add `default_factory` argument to `Field` to create a dynamic default value by passing a zero-argument callable, [#1210](https://github.com/pydantic/pydantic/pull/1210)\ by [@prettywood](https://github.com/prettywood)\ \ * add support for `NewType` of `List`, `Optional`, etc, [#1207](https://github.com/pydantic/pydantic/pull/1207)\ by [@Kazy](https://github.com/Kazy)\ \ * fix mypy signature for `root_validator`, [#1192](https://github.com/pydantic/pydantic/pull/1192)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fixed parsing of nested 'custom root type' models, [#1190](https://github.com/pydantic/pydantic/pull/1190)\ by [@Shados](https://github.com/Shados)\ \ * Add `validate_arguments` function decorator which checks the arguments to a function matches type annotations, [#1179](https://github.com/pydantic/pydantic/pull/1179)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add `__signature__` to models, [#1034](https://github.com/pydantic/pydantic/pull/1034)\ by [@Bobronium](https://github.com/Bobronium)\ \ * Refactor `._iter()` method, 10x speed boost for `dict(model)`, [#1017](https://github.com/pydantic/pydantic/pull/1017)\ by [@Bobronium](https://github.com/Bobronium)\ \ \ v1.4 (2020-01-24)[¶](#v14-2020-01-24 "Permanent link")\ \ -------------------------------------------------------\ \ * **Breaking Change:** alias precedence logic changed so aliases on a field always take priority over an alias from `alias_generator` to avoid buggy/unexpected behaviour, see [here](https://docs.pydantic.dev/usage/model_config/#alias-precedence)\ for details, [#1178](https://github.com/pydantic/pydantic/pull/1178)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add support for unicode and punycode in TLDs, [#1182](https://github.com/pydantic/pydantic/pull/1182)\ by [@jamescurtin](https://github.com/jamescurtin)\ \ * Fix `cls` argument in validators during assignment, [#1172](https://github.com/pydantic/pydantic/pull/1172)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * completing Luhn algorithm for `PaymentCardNumber`, [#1166](https://github.com/pydantic/pydantic/pull/1166)\ by [@cuencandres](https://github.com/cuencandres)\ \ * add support for generics that implement `__get_validators__` like a custom data type, [#1159](https://github.com/pydantic/pydantic/pull/1159)\ by [@tiangolo](https://github.com/tiangolo)\ \ * add support for infinite generators with `Iterable`, [#1152](https://github.com/pydantic/pydantic/pull/1152)\ by [@tiangolo](https://github.com/tiangolo)\ \ * fix `url_regex` to accept schemas with `+`, `-` and `.` after the first character, [#1142](https://github.com/pydantic/pydantic/pull/1142)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * move `version_info()` to `version.py`, suggest its use in issues, [#1138](https://github.com/pydantic/pydantic/pull/1138)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Improve pydantic import time by roughly 50% by deferring some module loading and regex compilation, [#1127](https://github.com/pydantic/pydantic/pull/1127)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix `EmailStr` and `NameEmail` to accept instances of themselves in cython, [#1126](https://github.com/pydantic/pydantic/pull/1126)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * Pass model class to the `Config.schema_extra` callable, [#1125](https://github.com/pydantic/pydantic/pull/1125)\ by [@therefromhere](https://github.com/therefromhere)\ \ * Fix regex for username and password in URLs, [#1115](https://github.com/pydantic/pydantic/pull/1115)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add support for nested generic models, [#1104](https://github.com/pydantic/pydantic/pull/1104)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add `__all__` to `__init__.py` to prevent "implicit reexport" errors from mypy, [#1072](https://github.com/pydantic/pydantic/pull/1072)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add support for using "dotenv" files with `BaseSettings`, [#1011](https://github.com/pydantic/pydantic/pull/1011)\ by [@acnebs](https://github.com/acnebs)\ \ \ v1.3 (2019-12-21)[¶](#v13-2019-12-21 "Permanent link")\ \ -------------------------------------------------------\ \ * Change `schema` and `schema_model` to handle dataclasses by using their `__pydantic_model__` feature, [#792](https://github.com/pydantic/pydantic/pull/792)\ by [@aviramha](https://github.com/aviramha)\ \ * Added option for `root_validator` to be skipped if values validation fails using keyword `skip_on_failure=True`, [#1049](https://github.com/pydantic/pydantic/pull/1049)\ by [@aviramha](https://github.com/aviramha)\ \ * Allow `Config.schema_extra` to be a callable so that the generated schema can be post-processed, [#1054](https://github.com/pydantic/pydantic/pull/1054)\ by [@selimb](https://github.com/selimb)\ \ * Update mypy to version 0.750, [#1057](https://github.com/pydantic/pydantic/pull/1057)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Trick Cython into allowing str subclassing, [#1061](https://github.com/pydantic/pydantic/pull/1061)\ by [@skewty](https://github.com/skewty)\ \ * Prevent type attributes being added to schema unless the attribute `__schema_attributes__` is `True`, [#1064](https://github.com/pydantic/pydantic/pull/1064)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Change `BaseModel.parse_file` to use `Config.json_loads`, [#1067](https://github.com/pydantic/pydantic/pull/1067)\ by [@kierandarcy](https://github.com/kierandarcy)\ \ * Fix for optional `Json` fields, [#1073](https://github.com/pydantic/pydantic/pull/1073)\ by [@volker48](https://github.com/volker48)\ \ * Change the default number of threads used when compiling with cython to one, allow override via the `CYTHON_NTHREADS` environment variable, [#1074](https://github.com/pydantic/pydantic/pull/1074)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Run FastAPI tests during Pydantic's CI tests, [#1075](https://github.com/pydantic/pydantic/pull/1075)\ by [@tiangolo](https://github.com/tiangolo)\ \ * My mypy strictness constraints, and associated tweaks to type annotations, [#1077](https://github.com/pydantic/pydantic/pull/1077)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add `__eq__` to SecretStr and SecretBytes to allow "value equals", [#1079](https://github.com/pydantic/pydantic/pull/1079)\ by [@sbv-trueenergy](https://github.com/sbv-trueenergy)\ \ * Fix schema generation for nested None case, [#1088](https://github.com/pydantic/pydantic/pull/1088)\ by [@lutostag](https://github.com/lutostag)\ \ * Consistent checks for sequence like objects, [#1090](https://github.com/pydantic/pydantic/pull/1090)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix `Config` inheritance on `BaseSettings` when used with `env_prefix`, [#1091](https://github.com/pydantic/pydantic/pull/1091)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix for `__modify_schema__` when it conflicted with `field_class_to_schema*`, [#1102](https://github.com/pydantic/pydantic/pull/1102)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * docs: Fix explanation of case sensitive environment variable names when populating `BaseSettings` subclass attributes, [#1105](https://github.com/pydantic/pydantic/pull/1105)\ by [@tribals](https://github.com/tribals)\ \ * Rename django-rest-framework benchmark in documentation, [#1119](https://github.com/pydantic/pydantic/pull/1119)\ by [@frankie567](https://github.com/frankie567)\ \ \ v1.2 (2019-11-28)[¶](#v12-2019-11-28 "Permanent link")\ \ -------------------------------------------------------\ \ * **Possible Breaking Change:** Add support for required `Optional` with `name: Optional[AnyType] = Field(...)` and refactor `ModelField` creation to preserve `required` parameter value, [#1031](https://github.com/pydantic/pydantic/pull/1031)\ by [@tiangolo](https://github.com/tiangolo)\ ; see [here](https://docs.pydantic.dev/usage/models/#required-optional-fields)\ for details\ * Add benchmarks for `cattrs`, [#513](https://github.com/pydantic/pydantic/pull/513)\ by [@sebastianmika](https://github.com/sebastianmika)\ \ * Add `exclude_none` option to `dict()` and friends, [#587](https://github.com/pydantic/pydantic/pull/587)\ by [@niknetniko](https://github.com/niknetniko)\ \ * Add benchmarks for `valideer`, [#670](https://github.com/pydantic/pydantic/pull/670)\ by [@gsakkis](https://github.com/gsakkis)\ \ * Add `parse_obj_as` and `parse_file_as` functions for ad-hoc parsing of data into arbitrary pydantic-compatible types, [#934](https://github.com/pydantic/pydantic/pull/934)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Add `allow_reuse` argument to validators, thus allowing validator reuse, [#940](https://github.com/pydantic/pydantic/pull/940)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Add support for mapping types for custom root models, [#958](https://github.com/pydantic/pydantic/pull/958)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Mypy plugin support for dataclasses, [#966](https://github.com/pydantic/pydantic/pull/966)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * Add support for dataclasses default factory, [#968](https://github.com/pydantic/pydantic/pull/968)\ by [@ahirner](https://github.com/ahirner)\ \ * Add a `ByteSize` type for converting byte string (`1GB`) to plain bytes, [#977](https://github.com/pydantic/pydantic/pull/977)\ by [@dgasmith](https://github.com/dgasmith)\ \ * Fix mypy complaint about `@root_validator(pre=True)`, [#984](https://github.com/pydantic/pydantic/pull/984)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add manylinux binaries for Python 3.8 to pypi, also support manylinux2010, [#994](https://github.com/pydantic/pydantic/pull/994)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Adds ByteSize conversion to another unit, [#995](https://github.com/pydantic/pydantic/pull/995)\ by [@dgasmith](https://github.com/dgasmith)\ \ * Fix `__str__` and `__repr__` inheritance for models, [#1022](https://github.com/pydantic/pydantic/pull/1022)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add testimonials section to docs, [#1025](https://github.com/pydantic/pydantic/pull/1025)\ by [@sullivancolin](https://github.com/sullivancolin)\ \ * Add support for `typing.Literal` for Python 3.8, [#1026](https://github.com/pydantic/pydantic/pull/1026)\ by [@dmontagu](https://github.com/dmontagu)\ \ \ v1.1.1 (2019-11-20)[¶](#v111-2019-11-20 "Permanent link")\ \ ----------------------------------------------------------\ \ * Fix bug where use of complex fields on sub-models could cause fields to be incorrectly configured, [#1015](https://github.com/pydantic/pydantic/pull/1015)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v1.1 (2019-11-07)[¶](#v11-2019-11-07 "Permanent link")\ \ -------------------------------------------------------\ \ * Add a mypy plugin for type checking `BaseModel.__init__` and more, [#722](https://github.com/pydantic/pydantic/pull/722)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Change return type typehint for `GenericModel.__class_getitem__` to prevent PyCharm warnings, [#936](https://github.com/pydantic/pydantic/pull/936)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Fix usage of `Any` to allow `None`, also support `TypeVar` thus allowing use of un-parameterised collection types e.g. `Dict` and `List`, [#962](https://github.com/pydantic/pydantic/pull/962)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Set `FieldInfo` on subfields to fix schema generation for complex nested types, [#965](https://github.com/pydantic/pydantic/pull/965)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v1.0 (2019-10-23)[¶](#v10-2019-10-23 "Permanent link")\ \ -------------------------------------------------------\ \ * **Breaking Change:** deprecate the `Model.fields` property, use `Model.__fields__` instead, [#883](https://github.com/pydantic/pydantic/pull/883)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking Change:** Change the precedence of aliases so child model aliases override parent aliases, including using `alias_generator`, [#904](https://github.com/pydantic/pydantic/pull/904)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking change:** Rename `skip_defaults` to `exclude_unset`, and add ability to exclude actual defaults, [#915](https://github.com/pydantic/pydantic/pull/915)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Add `**kwargs` to `pydantic.main.ModelMetaclass.__new__` so `__init_subclass__` can take custom parameters on extended `BaseModel` classes, [#867](https://github.com/pydantic/pydantic/pull/867)\ by [@retnikt](https://github.com/retnikt)\ \ * Fix field of a type that has a default value, [#880](https://github.com/pydantic/pydantic/pull/880)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * Use `FutureWarning` instead of `DeprecationWarning` when `alias` instead of `env` is used for settings models, [#881](https://github.com/pydantic/pydantic/pull/881)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix issue with `BaseSettings` inheritance and `alias` getting set to `None`, [#882](https://github.com/pydantic/pydantic/pull/882)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Modify `__repr__` and `__str__` methods to be consistent across all public classes, add `__pretty__` to support python-devtools, [#884](https://github.com/pydantic/pydantic/pull/884)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * deprecation warning for `case_insensitive` on `BaseSettings` config, [#885](https://github.com/pydantic/pydantic/pull/885)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * For `BaseSettings` 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](https://github.com/pydantic/pydantic/pull/888)\ by [@idmitrievsky](https://github.com/idmitrievsky)\ \ * change secret types example, [#890](https://github.com/pydantic/pydantic/pull/890)\ by [@ashears](https://github.com/ashears)\ \ * Change the signature of `Model.construct()` to be more user-friendly, document `construct()` usage, [#898](https://github.com/pydantic/pydantic/pull/898)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add example for the `construct()` method, [#907](https://github.com/pydantic/pydantic/pull/907)\ by [@ashears](https://github.com/ashears)\ \ * Improve use of `Field` 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](https://github.com/pydantic/pydantic/pull/909)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * update docs for bool missing valid value, [#911](https://github.com/pydantic/pydantic/pull/911)\ by [@trim21](https://github.com/trim21)\ \ * Better `str`/`repr` logic for `ModelField`, [#912](https://github.com/pydantic/pydantic/pull/912)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix `ConstrainedList`, update schema generation to reflect `min_items` and `max_items` `Field()` arguments, [#917](https://github.com/pydantic/pydantic/pull/917)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Allow abstracts sets (eg. dict keys) in the `include` and `exclude` arguments of `dict()`, [#921](https://github.com/pydantic/pydantic/pull/921)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix JSON serialization errors on `ValidationError.json()` by using `pydantic_encoder`, [#922](https://github.com/pydantic/pydantic/pull/922)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Clarify usage of `remove_untouched`, improve error message for types with no validators, [#926](https://github.com/pydantic/pydantic/pull/926)\ by [@retnikt](https://github.com/retnikt)\ \ \ v1.0b2 (2019-10-07)[¶](#v10b2-2019-10-07 "Permanent link")\ \ -----------------------------------------------------------\ \ * Mark `StrictBool` typecheck as `bool` to allow for default values without mypy errors, [#690](https://github.com/pydantic/pydantic/pull/690)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Transfer the documentation build from sphinx to mkdocs, re-write much of the documentation, [#856](https://github.com/pydantic/pydantic/pull/856)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Add support for custom naming schemes for `GenericModel` subclasses, [#859](https://github.com/pydantic/pydantic/pull/859)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Add `if TYPE_CHECKING:` to the excluded lines for test coverage, [#874](https://github.com/pydantic/pydantic/pull/874)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Rename `allow_population_by_alias` to `allow_population_by_field_name`, remove unnecessary warning about it, [#875](https://github.com/pydantic/pydantic/pull/875)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v1.0b1 (2019-10-01)[¶](#v10b1-2019-10-01 "Permanent link")\ \ -----------------------------------------------------------\ \ * **Breaking Change:** rename `Schema` to `Field`, make it a function to placate mypy, [#577](https://github.com/pydantic/pydantic/pull/577)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking Change:** modify parsing behavior for `bool`, [#617](https://github.com/pydantic/pydantic/pull/617)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **Breaking Change:** `get_validators` is no longer recognised, use `__get_validators__`. `Config.ignore_extra` and `Config.allow_extra` are no longer recognised, use `Config.extra`, [#720](https://github.com/pydantic/pydantic/pull/720)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking Change:** modify default config settings for `BaseSettings`; `case_insensitive` renamed to `case_sensitive`, default changed to `case_sensitive = False`, `env_prefix` default changed to `''` - e.g. no prefix, [#721](https://github.com/pydantic/pydantic/pull/721)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **Breaking change:** Implement `root_validator` and rename root errors from `__obj__` to `__root__`, [#729](https://github.com/pydantic/pydantic/pull/729)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking Change:** alter the behaviour of `dict(model)` so that sub-models are nolonger converted to dictionaries, [#733](https://github.com/pydantic/pydantic/pull/733)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking change:** Added `initvars` support to `post_init_post_parse`, [#748](https://github.com/pydantic/pydantic/pull/748)\ by [@Raphael-C-Almeida](https://github.com/Raphael-C-Almeida)\ \ * **Breaking Change:** Make `BaseModel.json()` only serialize the `__root__` key for models with custom root, [#752](https://github.com/pydantic/pydantic/pull/752)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **Breaking Change:** complete rewrite of `URL` parsing logic, [#755](https://github.com/pydantic/pydantic/pull/755)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **Breaking Change:** preserve superclass annotations for field-determination when not provided in subclass, [#757](https://github.com/pydantic/pydantic/pull/757)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **Breaking Change:** `BaseSettings` now uses the special `env` settings to define which environment variables to read, not aliases, [#847](https://github.com/pydantic/pydantic/pull/847)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add support for `assert` statements inside validators, [#653](https://github.com/pydantic/pydantic/pull/653)\ by [@abdusco](https://github.com/abdusco)\ \ * Update documentation to specify the use of `pydantic.dataclasses.dataclass` and subclassing `pydantic.BaseModel`, [#710](https://github.com/pydantic/pydantic/pull/710)\ by [@maddosaurus](https://github.com/maddosaurus)\ \ * Allow custom JSON decoding and encoding via `json_loads` and `json_dumps` `Config` properties, [#714](https://github.com/pydantic/pydantic/pull/714)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * make all annotated fields occur in the order declared, [#715](https://github.com/pydantic/pydantic/pull/715)\ by [@dmontagu](https://github.com/dmontagu)\ \ * use pytest to test `mypy` integration, [#735](https://github.com/pydantic/pydantic/pull/735)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add `__repr__` method to `ErrorWrapper`, [#738](https://github.com/pydantic/pydantic/pull/738)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Added support for `FrozenSet` members in dataclasses, and a better error when attempting to use types from the `typing` module that are not supported by Pydantic, [#745](https://github.com/pydantic/pydantic/pull/745)\ by [@djpetti](https://github.com/djpetti)\ \ * add documentation for Pycharm Plugin, [#750](https://github.com/pydantic/pydantic/pull/750)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * fix broken examples in the docs, [#753](https://github.com/pydantic/pydantic/pull/753)\ by [@dmontagu](https://github.com/dmontagu)\ \ * moving typing related objects into `pydantic.typing`, [#761](https://github.com/pydantic/pydantic/pull/761)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Minor performance improvements to `ErrorWrapper`, `ValidationError` and datetime parsing, [#763](https://github.com/pydantic/pydantic/pull/763)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Improvements to `datetime`/`date`/`time`/`timedelta` types: more descriptive errors, change errors to `value_error` not `type_error`, support bytes, [#766](https://github.com/pydantic/pydantic/pull/766)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix error messages for `Literal` types with multiple allowed values, [#770](https://github.com/pydantic/pydantic/pull/770)\ by [@dmontagu](https://github.com/dmontagu)\ \ * Improved auto-generated `title` field in JSON schema by converting underscore to space, [#772](https://github.com/pydantic/pydantic/pull/772)\ by [@skewty](https://github.com/skewty)\ \ * support `mypy --no-implicit-reexport` for dataclasses, also respect `--no-implicit-reexport` in pydantic itself, [#783](https://github.com/pydantic/pydantic/pull/783)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add the `PaymentCardNumber` type, [#790](https://github.com/pydantic/pydantic/pull/790)\ by [@matin](https://github.com/matin)\ \ * Fix const validations for lists, [#794](https://github.com/pydantic/pydantic/pull/794)\ by [@hmvp](https://github.com/hmvp)\ \ * Set `additionalProperties` to false in schema for models with extra fields disallowed, [#796](https://github.com/pydantic/pydantic/pull/796)\ by [@Code0x58](https://github.com/Code0x58)\ \ * `EmailStr` validation method now returns local part case-sensitive per RFC 5321, [#798](https://github.com/pydantic/pydantic/pull/798)\ by [@henriklindgren](https://github.com/henriklindgren)\ \ * Added ability to validate strictness to `ConstrainedFloat`, `ConstrainedInt` and `ConstrainedStr` and added `StrictFloat` and `StrictInt` classes, [#799](https://github.com/pydantic/pydantic/pull/799)\ by [@DerRidda](https://github.com/DerRidda)\ \ * Improve handling of `None` and `Optional`, replace `whole` with `each_item` (inverse meaning, default `False`) on validators, [#803](https://github.com/pydantic/pydantic/pull/803)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add support for `Type[T]` type hints, [#807](https://github.com/pydantic/pydantic/pull/807)\ by [@timonbimon](https://github.com/timonbimon)\ \ * Performance improvements from removing `change_exceptions`, change how pydantic error are constructed, [#819](https://github.com/pydantic/pydantic/pull/819)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix the error message arising when a `BaseModel`\-type model field causes a `ValidationError` during parsing, [#820](https://github.com/pydantic/pydantic/pull/820)\ by [@dmontagu](https://github.com/dmontagu)\ \ * allow `getter_dict` on `Config`, modify `GetterDict` to be more like a `Mapping` object and thus easier to work with, [#821](https://github.com/pydantic/pydantic/pull/821)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Only check `TypeVar` param on base `GenericModel` class, [#842](https://github.com/pydantic/pydantic/pull/842)\ by [@zpencerq](https://github.com/zpencerq)\ \ * rename `Model._schema_cache` -> `Model.__schema_cache__`, `Model._json_encoder` -> `Model.__json_encoder__`, `Model._custom_root_type` -> `Model.__custom_root_type__`, [#851](https://github.com/pydantic/pydantic/pull/851)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.32.2 (2019-08-17)[¶](#v0322-2019-08-17 "Permanent link")\ \ ------------------------------------------------------------\ \ (Docs are available [here](https://5d584fcca7c9b70007d1c997--pydantic-docs.netlify.com)\ )\ \ * fix `__post_init__` usage with dataclass inheritance, fix [#739](https://github.com/pydantic/pydantic/pull/739)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix required fields validation on GenericModels classes, [#742](https://github.com/pydantic/pydantic/pull/742)\ by [@amitbl](https://github.com/amitbl)\ \ * fix defining custom `Schema` on `GenericModel` fields, [#754](https://github.com/pydantic/pydantic/pull/754)\ by [@amitbl](https://github.com/amitbl)\ \ \ v0.32.1 (2019-08-08)[¶](#v0321-2019-08-08 "Permanent link")\ \ ------------------------------------------------------------\ \ * do not validate extra fields when `validate_assignment` is on, [#724](https://github.com/pydantic/pydantic/pull/724)\ by [@YaraslauZhylko](https://github.com/YaraslauZhylko)\ \ \ v0.32 (2019-08-06)[¶](#v032-2019-08-06 "Permanent link")\ \ ---------------------------------------------------------\ \ * add model name to `ValidationError` error message, [#676](https://github.com/pydantic/pydantic/pull/676)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **breaking change**: remove `__getattr__` and rename `__values__` to `__dict__` on `BaseModel`, deprecation warning on use `__values__` attr, attributes access speed increased up to 14 times, [#712](https://github.com/pydantic/pydantic/pull/712)\ by [@Bobronium](https://github.com/Bobronium)\ \ * support `ForwardRef` (without self-referencing annotations) in Python 3.6, [#706](https://github.com/pydantic/pydantic/pull/706)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * implement `schema_extra` in `Config` sub-class, [#663](https://github.com/pydantic/pydantic/pull/663)\ by [@tiangolo](https://github.com/tiangolo)\ \ \ v0.31.1 (2019-07-31)[¶](#v0311-2019-07-31 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix json generation for `EnumError`, [#697](https://github.com/pydantic/pydantic/pull/697)\ by [@dmontagu](https://github.com/dmontagu)\ \ * update numerous dependencies\ \ v0.31 (2019-07-24)[¶](#v031-2019-07-24 "Permanent link")\ \ ---------------------------------------------------------\ \ * better support for floating point `multiple_of` values, [#652](https://github.com/pydantic/pydantic/pull/652)\ by [@justindujardin](https://github.com/justindujardin)\ \ * fix schema generation for `NewType` and `Literal`, [#649](https://github.com/pydantic/pydantic/pull/649)\ by [@dmontagu](https://github.com/dmontagu)\ \ * fix `alias_generator` and field config conflict, [#645](https://github.com/pydantic/pydantic/pull/645)\ by [@gmetzker](https://github.com/gmetzker)\ and [#658](https://github.com/pydantic/pydantic/pull/658)\ by [@Bobronium](https://github.com/Bobronium)\ \ * more detailed message for `EnumError`, [#673](https://github.com/pydantic/pydantic/pull/673)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add advanced exclude support for `dict`, `json` and `copy`, [#648](https://github.com/pydantic/pydantic/pull/648)\ by [@Bobronium](https://github.com/Bobronium)\ \ * fix bug in `GenericModel` for models with concrete parameterized fields, [#672](https://github.com/pydantic/pydantic/pull/672)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add documentation for `Literal` type, [#651](https://github.com/pydantic/pydantic/pull/651)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add `Config.keep_untouched` for custom descriptors support, [#679](https://github.com/pydantic/pydantic/pull/679)\ by [@Bobronium](https://github.com/Bobronium)\ \ * use `inspect.cleandoc` internally to get model description, [#657](https://github.com/pydantic/pydantic/pull/657)\ by [@tiangolo](https://github.com/tiangolo)\ \ * add `Color` to schema generation, by [@euri10](https://github.com/euri10)\ \ * add documentation for Literal type, [#651](https://github.com/pydantic/pydantic/pull/651)\ by [@dmontagu](https://github.com/dmontagu)\ \ \ v0.30.1 (2019-07-15)[¶](#v0301-2019-07-15 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix so nested classes which inherit and change `__init__` are correctly processed while still allowing `self` as a parameter, [#644](https://github.com/pydantic/pydantic/pull/644)\ by [@lnaden](https://github.com/lnaden)\ and [@dgasmith](https://github.com/dgasmith)\ \ \ v0.30 (2019-07-07)[¶](#v030-2019-07-07 "Permanent link")\ \ ---------------------------------------------------------\ \ * enforce single quotes in code, [#612](https://github.com/pydantic/pydantic/pull/612)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix infinite recursion with dataclass inheritance and `__post_init__`, [#606](https://github.com/pydantic/pydantic/pull/606)\ by [@Hanaasagi](https://github.com/Hanaasagi)\ \ * fix default values for `GenericModel`, [#610](https://github.com/pydantic/pydantic/pull/610)\ by [@dmontagu](https://github.com/dmontagu)\ \ * clarify that self-referencing models require Python 3.7+, [#616](https://github.com/pydantic/pydantic/pull/616)\ by [@vlcinsky](https://github.com/vlcinsky)\ \ * fix truncate for types, [#611](https://github.com/pydantic/pydantic/pull/611)\ by [@dmontagu](https://github.com/dmontagu)\ \ * add `alias_generator` support, [#622](https://github.com/pydantic/pydantic/pull/622)\ by [@Bobronium](https://github.com/Bobronium)\ \ * fix unparameterized generic type schema generation, [#625](https://github.com/pydantic/pydantic/pull/625)\ by [@dmontagu](https://github.com/dmontagu)\ \ * fix schema generation with multiple/circular references to the same model, [#621](https://github.com/pydantic/pydantic/pull/621)\ by [@tiangolo](https://github.com/tiangolo)\ and [@wongpat](https://github.com/wongpat)\ \ * support custom root types, [#628](https://github.com/pydantic/pydantic/pull/628)\ by [@koxudaxi](https://github.com/koxudaxi)\ \ * support `self` as a field name in `parse_obj`, [#632](https://github.com/pydantic/pydantic/pull/632)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.29 (2019-06-19)[¶](#v029-2019-06-19 "Permanent link")\ \ ---------------------------------------------------------\ \ * support dataclasses.InitVar, [#592](https://github.com/pydantic/pydantic/pull/592)\ by [@pfrederiks](https://github.com/pfrederiks)\ \ * Updated documentation to elucidate the usage of `Union` when defining multiple types under an attribute's annotation and showcase how the type-order can affect marshalling of provided values, [#594](https://github.com/pydantic/pydantic/pull/594)\ by [@somada141](https://github.com/somada141)\ \ * add `conlist` type, [#583](https://github.com/pydantic/pydantic/pull/583)\ by [@hmvp](https://github.com/hmvp)\ \ * add support for generics, [#595](https://github.com/pydantic/pydantic/pull/595)\ by [@dmontagu](https://github.com/dmontagu)\ \ \ v0.28 (2019-06-06)[¶](#v028-2019-06-06 "Permanent link")\ \ ---------------------------------------------------------\ \ * fix support for JSON Schema generation when using models with circular references in Python 3.7, [#572](https://github.com/pydantic/pydantic/pull/572)\ by [@tiangolo](https://github.com/tiangolo)\ \ * support `__post_init_post_parse__` on dataclasses, [#567](https://github.com/pydantic/pydantic/pull/567)\ by [@sevaho](https://github.com/sevaho)\ \ * allow dumping dataclasses to JSON, [#575](https://github.com/pydantic/pydantic/pull/575)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ and [@DanielOberg](https://github.com/DanielOberg)\ \ * ORM mode, [#562](https://github.com/pydantic/pydantic/pull/562)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix `pydantic.compiled` on ipython, [#573](https://github.com/pydantic/pydantic/pull/573)\ by [@dmontagu](https://github.com/dmontagu)\ and [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add `StrictBool` type, [#579](https://github.com/pydantic/pydantic/pull/579)\ by [@cazgp](https://github.com/cazgp)\ \ \ v0.27 (2019-05-30)[¶](#v027-2019-05-30 "Permanent link")\ \ ---------------------------------------------------------\ \ * **breaking change** `_pydantic_post_init` to execute dataclass' original `__post_init__` before validation, [#560](https://github.com/pydantic/pydantic/pull/560)\ by [@HeavenVolkoff](https://github.com/HeavenVolkoff)\ \ * fix handling of generic types without specified parameters, [#550](https://github.com/pydantic/pydantic/pull/550)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **breaking change** (maybe): this is the first release compiled with **cython**, see the docs and please submit an issue if you run into problems\ \ v0.27.0a1 (2019-05-26)[¶](#v0270a1-2019-05-26 "Permanent link")\ \ ----------------------------------------------------------------\ \ * fix JSON Schema for `list`, `tuple`, and `set`, [#540](https://github.com/pydantic/pydantic/pull/540)\ by [@tiangolo](https://github.com/tiangolo)\ \ * compiling with cython, `manylinux` binaries, some other performance improvements, [#548](https://github.com/pydantic/pydantic/pull/548)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.26 (2019-05-22)[¶](#v026-2019-05-22 "Permanent link")\ \ ---------------------------------------------------------\ \ * fix to schema generation for `IPvAnyAddress`, `IPvAnyInterface`, `IPvAnyNetwork` [#498](https://github.com/pydantic/pydantic/pull/498)\ by [@pilosus](https://github.com/pilosus)\ \ * fix variable length tuples support, [#495](https://github.com/pydantic/pydantic/pull/495)\ by [@pilosus](https://github.com/pilosus)\ \ * fix return type hint for `create_model`, [#526](https://github.com/pydantic/pydantic/pull/526)\ by [@dmontagu](https://github.com/dmontagu)\ \ * **Breaking Change:** fix `.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](https://github.com/pydantic/pydantic/pull/517)\ by [@sommd](https://github.com/sommd)\ \ * fix to schema generation for `IPv4Address`, `IPv6Address`, `IPv4Interface`, `IPv6Interface`, `IPv4Network`, `IPv6Network` [#532](https://github.com/pydantic/pydantic/pull/532)\ by [@euri10](https://github.com/euri10)\ \ * add `Color` type, [#504](https://github.com/pydantic/pydantic/pull/504)\ by [@pilosus](https://github.com/pilosus)\ and [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.25 (2019-05-05)[¶](#v025-2019-05-05 "Permanent link")\ \ ---------------------------------------------------------\ \ * Improve documentation on self-referencing models and annotations, [#487](https://github.com/pydantic/pydantic/pull/487)\ by [@theenglishway](https://github.com/theenglishway)\ \ * fix `.dict()` with extra keys, [#490](https://github.com/pydantic/pydantic/pull/490)\ by [@JaewonKim](https://github.com/JaewonKim)\ \ * support `const` keyword in `Schema`, [#434](https://github.com/pydantic/pydantic/pull/434)\ by [@Sean1708](https://github.com/Sean1708)\ \ \ v0.24 (2019-04-23)[¶](#v024-2019-04-23 "Permanent link")\ \ ---------------------------------------------------------\ \ * fix handling `ForwardRef` in sub-types, like `Union`, [#464](https://github.com/pydantic/pydantic/pull/464)\ by [@tiangolo](https://github.com/tiangolo)\ \ * fix secret serialization, [#465](https://github.com/pydantic/pydantic/pull/465)\ by [@atheuz](https://github.com/atheuz)\ \ * Support custom validators for dataclasses, [#454](https://github.com/pydantic/pydantic/pull/454)\ by [@primal100](https://github.com/primal100)\ \ * fix `parse_obj` to cope with dict-like objects, [#472](https://github.com/pydantic/pydantic/pull/472)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix to schema generation in nested dataclass-based models, [#474](https://github.com/pydantic/pydantic/pull/474)\ by [@NoAnyLove](https://github.com/NoAnyLove)\ \ * fix `json` for `Path`, `FilePath`, and `DirectoryPath` objects, [#473](https://github.com/pydantic/pydantic/pull/473)\ by [@mikegoodspeed](https://github.com/mikegoodspeed)\ \ \ v0.23 (2019-04-04)[¶](#v023-2019-04-04 "Permanent link")\ \ ---------------------------------------------------------\ \ * improve documentation for contributing section, [#441](https://github.com/pydantic/pydantic/pull/441)\ by [@pilosus](https://github.com/pilosus)\ \ * improve README.rst to include essential information about the package, [#446](https://github.com/pydantic/pydantic/pull/446)\ by [@pilosus](https://github.com/pilosus)\ \ * `IntEnum` support, [#444](https://github.com/pydantic/pydantic/pull/444)\ by [@potykion](https://github.com/potykion)\ \ * fix PyObject callable value, [#409](https://github.com/pydantic/pydantic/pull/409)\ by [@pilosus](https://github.com/pilosus)\ \ * fix `black` deprecation warnings after update, [#451](https://github.com/pydantic/pydantic/pull/451)\ by [@pilosus](https://github.com/pilosus)\ \ * fix `ForwardRef` collection bug, [#450](https://github.com/pydantic/pydantic/pull/450)\ by [@tigerwings](https://github.com/tigerwings)\ \ * Support specialized `ClassVars`, [#455](https://github.com/pydantic/pydantic/pull/455)\ by [@tyrylu](https://github.com/tyrylu)\ \ * fix JSON serialization for `ipaddress` types, [#333](https://github.com/pydantic/pydantic/pull/333)\ by [@pilosus](https://github.com/pilosus)\ \ * add `SecretStr` and `SecretBytes` types, [#452](https://github.com/pydantic/pydantic/pull/452)\ by [@atheuz](https://github.com/atheuz)\ \ \ v0.22 (2019-03-29)[¶](#v022-2019-03-29 "Permanent link")\ \ ---------------------------------------------------------\ \ * add `IPv{4,6,Any}Network` and `IPv{4,6,Any}Interface` types from `ipaddress` stdlib, [#333](https://github.com/pydantic/pydantic/pull/333)\ by [@pilosus](https://github.com/pilosus)\ \ * add docs for `datetime` types, [#386](https://github.com/pydantic/pydantic/pull/386)\ by [@pilosus](https://github.com/pilosus)\ \ * fix to schema generation in dataclass-based models, [#408](https://github.com/pydantic/pydantic/pull/408)\ by [@pilosus](https://github.com/pilosus)\ \ * fix path in nested models, [#437](https://github.com/pydantic/pydantic/pull/437)\ by [@kataev](https://github.com/kataev)\ \ * add `Sequence` support, [#304](https://github.com/pydantic/pydantic/pull/304)\ by [@pilosus](https://github.com/pilosus)\ \ \ v0.21.0 (2019-03-15)[¶](#v0210-2019-03-15 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix typo in `NoneIsNotAllowedError` message, [#414](https://github.com/pydantic/pydantic/pull/414)\ by [@YaraslauZhylko](https://github.com/YaraslauZhylko)\ \ * add `IPvAnyAddress`, `IPv4Address` and `IPv6Address` types, [#333](https://github.com/pydantic/pydantic/pull/333)\ by [@pilosus](https://github.com/pilosus)\ \ \ v0.20.1 (2019-02-26)[¶](#v0201-2019-02-26 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix type hints of `parse_obj` and similar methods, [#405](https://github.com/pydantic/pydantic/pull/405)\ by [@erosennin](https://github.com/erosennin)\ \ * fix submodel validation, [#403](https://github.com/pydantic/pydantic/pull/403)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * correct type hints for `ValidationError.json`, [#406](https://github.com/pydantic/pydantic/pull/406)\ by [@layday](https://github.com/layday)\ \ \ v0.20.0 (2019-02-18)[¶](#v0200-2019-02-18 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix tests for Python 3.8, [#396](https://github.com/pydantic/pydantic/pull/396)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Adds fields to the `dir` method for autocompletion in interactive sessions, [#398](https://github.com/pydantic/pydantic/pull/398)\ by [@dgasmith](https://github.com/dgasmith)\ \ * support `ForwardRef` (and therefore `from __future__ import annotations`) with dataclasses, [#397](https://github.com/pydantic/pydantic/pull/397)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.20.0a1 (2019-02-13)[¶](#v0200a1-2019-02-13 "Permanent link")\ \ ----------------------------------------------------------------\ \ * **breaking change** (maybe): more sophisticated argument parsing for validators, any subset of `values`, `config` and `field` is now permitted, eg. `(cls, value, field)`, however the variadic key word argument ("`**kwargs`") **must** be called `kwargs`, [#388](https://github.com/pydantic/pydantic/pull/388)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **breaking change**: Adds `skip_defaults` argument to `BaseModel.dict()` to allow skipping of fields that were not explicitly set, signature of `Model.construct()` changed, [#389](https://github.com/pydantic/pydantic/pull/389)\ by [@dgasmith](https://github.com/dgasmith)\ \ * add `py.typed` marker file for PEP-561 support, [#391](https://github.com/pydantic/pydantic/pull/391)\ by [@je-l](https://github.com/je-l)\ \ * Fix `extra` behaviour for multiple inheritance/mix-ins, [#394](https://github.com/pydantic/pydantic/pull/394)\ by [@YaraslauZhylko](https://github.com/YaraslauZhylko)\ \ \ v0.19.0 (2019-02-04)[¶](#v0190-2019-02-04 "Permanent link")\ \ ------------------------------------------------------------\ \ * Support `Callable` type hint, fix [#279](https://github.com/pydantic/pydantic/pull/279)\ by [@proofit404](https://github.com/proofit404)\ \ * Fix schema for fields with `validator` decorator, fix [#375](https://github.com/pydantic/pydantic/pull/375)\ by [@tiangolo](https://github.com/tiangolo)\ \ * Add `multiple_of` constraint to `ConstrainedDecimal`, `ConstrainedFloat`, `ConstrainedInt` and their related types `condecimal`, `confloat`, and `conint` [#371](https://github.com/pydantic/pydantic/pull/371)\ , thanks [@StephenBrown2](https://github.com/StephenBrown2)\ \ * Deprecated `ignore_extra` and `allow_extra` Config fields in favor of `extra`, [#352](https://github.com/pydantic/pydantic/pull/352)\ by [@liiight](https://github.com/liiight)\ \ * Add type annotations to all functions, test fully with mypy, [#373](https://github.com/pydantic/pydantic/pull/373)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix for 'missing' error with `validate_all` or `validate_always`, [#381](https://github.com/pydantic/pydantic/pull/381)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Change the second/millisecond watershed for date/datetime parsing to `2e10`, [#385](https://github.com/pydantic/pydantic/pull/385)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.18.2 (2019-01-22)[¶](#v0182-2019-01-22 "Permanent link")\ \ ------------------------------------------------------------\ \ * Fix to schema generation with `Optional` fields, fix [#361](https://github.com/pydantic/pydantic/pull/361)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.18.1 (2019-01-17)[¶](#v0181-2019-01-17 "Permanent link")\ \ ------------------------------------------------------------\ \ * add `ConstrainedBytes` and `conbytes` types, [#315](https://github.com/pydantic/pydantic/pull/315)\ [@Gr1N](https://github.com/Gr1N)\ \ * adding `MANIFEST.in` to include license in package `.tar.gz`, [#358](https://github.com/pydantic/pydantic/pull/358)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.18.0 (2019-01-13)[¶](#v0180-2019-01-13 "Permanent link")\ \ ------------------------------------------------------------\ \ * **breaking change**: don't call validators on keys of dictionaries, [#254](https://github.com/pydantic/pydantic/pull/254)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * Fix validators with `always=True` when the default is `None` or the type is optional, also prevent `whole` validators being called for sub-fields, fix [#132](https://github.com/pydantic/pydantic/pull/132)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * improve documentation for settings priority and allow it to be easily changed, [#343](https://github.com/pydantic/pydantic/pull/343)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix `ignore_extra=False` and `allow_population_by_alias=True`, fix [#257](https://github.com/pydantic/pydantic/pull/257)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * **breaking change**: Set `BaseConfig` attributes `min_anystr_length` and `max_anystr_length` to `None` by default, fix [#349](https://github.com/pydantic/pydantic/pull/349)\ in [#350](https://github.com/pydantic/pydantic/pull/350)\ by [@tiangolo](https://github.com/tiangolo)\ \ * add support for postponed annotations, [#348](https://github.com/pydantic/pydantic/pull/348)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.17.0 (2018-12-27)[¶](#v0170-2018-12-27 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix schema for `timedelta` as number, [#325](https://github.com/pydantic/pydantic/pull/325)\ by [@tiangolo](https://github.com/tiangolo)\ \ * prevent validators being called repeatedly after inheritance, [#327](https://github.com/pydantic/pydantic/pull/327)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * prevent duplicate validator check in ipython, fix [#312](https://github.com/pydantic/pydantic/pull/312)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add "Using Pydantic" section to docs, [#323](https://github.com/pydantic/pydantic/pull/323)\ by [@tiangolo](https://github.com/tiangolo)\ & [#326](https://github.com/pydantic/pydantic/pull/326)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix schema generation for fields annotated as `: dict`, `: list`, `: tuple` and `: set`, [#330](https://github.com/pydantic/pydantic/pull/330)\ & [#335](https://github.com/pydantic/pydantic/pull/335)\ by [@nkonin](https://github.com/nkonin)\ \ * add support for constrained strings as dict keys in schema, [#332](https://github.com/pydantic/pydantic/pull/332)\ by [@tiangolo](https://github.com/tiangolo)\ \ * support for passing Config class in dataclasses decorator, [#276](https://github.com/pydantic/pydantic/pull/276)\ by [@jarekkar](https://github.com/jarekkar)\ (**breaking change**: this supersedes the `validate_assignment` argument with `config`)\ * support for nested dataclasses, [#334](https://github.com/pydantic/pydantic/pull/334)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * better errors when getting an `ImportError` with `PyObject`, [#309](https://github.com/pydantic/pydantic/pull/309)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * rename `get_validators` to `__get_validators__`, deprecation warning on use of old name, [#338](https://github.com/pydantic/pydantic/pull/338)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * support `ClassVar` by excluding such attributes from fields, [#184](https://github.com/pydantic/pydantic/pull/184)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.16.1 (2018-12-10)[¶](#v0161-2018-12-10 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix `create_model` to correctly use the passed `__config__`, [#320](https://github.com/pydantic/pydantic/pull/320)\ by [@hugoduncan](https://github.com/hugoduncan)\ \ \ v0.16.0 (2018-12-03)[¶](#v0160-2018-12-03 "Permanent link")\ \ ------------------------------------------------------------\ \ * **breaking change**: refactor schema generation to be compatible with JSON Schema and OpenAPI specs, [#308](https://github.com/pydantic/pydantic/pull/308)\ by [@tiangolo](https://github.com/tiangolo)\ \ * add `schema` to `schema` module to generate top-level schemas from base models, [#308](https://github.com/pydantic/pydantic/pull/308)\ by [@tiangolo](https://github.com/tiangolo)\ \ * add additional fields to `Schema` class to declare validation for `str` and numeric values, [#311](https://github.com/pydantic/pydantic/pull/311)\ by [@tiangolo](https://github.com/tiangolo)\ \ * rename `_schema` to `schema` on fields, [#318](https://github.com/pydantic/pydantic/pull/318)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * add `case_insensitive` option to `BaseSettings` `Config`, [#277](https://github.com/pydantic/pydantic/pull/277)\ by [@jasonkuhrt](https://github.com/jasonkuhrt)\ \ \ v0.15.0 (2018-11-18)[¶](#v0150-2018-11-18 "Permanent link")\ \ ------------------------------------------------------------\ \ * move codebase to use black, [#287](https://github.com/pydantic/pydantic/pull/287)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix alias use in settings, [#286](https://github.com/pydantic/pydantic/pull/286)\ by [@jasonkuhrt](https://github.com/jasonkuhrt)\ and [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix datetime parsing in `parse_date`, [#298](https://github.com/pydantic/pydantic/pull/298)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * allow dataclass inheritance, fix [#293](https://github.com/pydantic/pydantic/pull/293)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * fix `PyObject = None`, fix [#305](https://github.com/pydantic/pydantic/pull/305)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ * allow `Pattern` type, fix [#303](https://github.com/pydantic/pydantic/pull/303)\ by [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.14.0 (2018-10-02)[¶](#v0140-2018-10-02 "Permanent link")\ \ ------------------------------------------------------------\ \ * dataclasses decorator, [#269](https://github.com/pydantic/pydantic/pull/269)\ by [@Gaunt](https://github.com/Gaunt)\ and [@samuelcolvin](https://github.com/samuelcolvin)\ \ \ v0.13.1 (2018-09-21)[¶](#v0131-2018-09-21 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix issue where int\_validator doesn't cast a `bool` to an `int` [#264](https://github.com/pydantic/pydantic/pull/264)\ by [@nphyatt](https://github.com/nphyatt)\ \ * add deep copy support for `BaseModel.copy()` [#249](https://github.com/pydantic/pydantic/pull/249)\ , [@gangefors](https://github.com/gangefors)\ \ \ v0.13.0 (2018-08-25)[¶](#v0130-2018-08-25 "Permanent link")\ \ ------------------------------------------------------------\ \ * raise an exception if a field's name shadows an existing `BaseModel` attribute [#242](https://github.com/pydantic/pydantic/pull/242)\ \ * add `UrlStr` and `urlstr` types [#236](https://github.com/pydantic/pydantic/pull/236)\ \ * timedelta json encoding ISO8601 and total seconds, custom json encoders [#247](https://github.com/pydantic/pydantic/pull/247)\ , by [@cfkanesan](https://github.com/cfkanesan)\ and [@samuelcolvin](https://github.com/samuelcolvin)\ \ * allow `timedelta` objects as values for properties of type `timedelta` (matches `datetime` etc. behavior) [#247](https://github.com/pydantic/pydantic/pull/247)\ \ \ v0.12.1 (2018-07-31)[¶](#v0121-2018-07-31 "Permanent link")\ \ ------------------------------------------------------------\ \ * fix schema generation for fields defined using `typing.Any` [#237](https://github.com/pydantic/pydantic/pull/237)\ \ \ v0.12.0 (2018-07-31)[¶](#v0120-2018-07-31 "Permanent link")\ \ ------------------------------------------------------------\ \ * add `by_alias` argument in `.dict()` and `.json()` model methods [#205](https://github.com/pydantic/pydantic/pull/205)\ \ * add Json type support [#214](https://github.com/pydantic/pydantic/pull/214)\ \ * support tuples [#227](https://github.com/pydantic/pydantic/pull/227)\ \ * major improvements and changes to schema [#213](https://github.com/pydantic/pydantic/pull/213)\ \ \ v0.11.2 (2018-07-05)[¶](#v0112-2018-07-05 "Permanent link")\ \ ------------------------------------------------------------\ \ * add `NewType` support [#115](https://github.com/pydantic/pydantic/pull/115)\ \ * fix `list`, `set` & `tuple` validation [#225](https://github.com/pydantic/pydantic/pull/225)\ \ * separate out `validate_model` method, allow errors to be returned along with valid values [#221](https://github.com/pydantic/pydantic/pull/221)\ \ \ v0.11.1 (2018-07-02)[¶](#v0111-2018-07-02 "Permanent link")\ \ ------------------------------------------------------------\ \ * support Python 3.7 [#216](https://github.com/pydantic/pydantic/pull/216)\ , thanks [@layday](https://github.com/layday)\ \ * Allow arbitrary types in model [#209](https://github.com/pydantic/pydantic/pull/209)\ , thanks [@oldPadavan](https://github.com/oldPadavan)\ \ \ v0.11.0 (2018-06-28)[¶](#v0110-2018-06-28 "Permanent link")\ \ ------------------------------------------------------------\ \ * make `list`, `tuple` and `set` types stricter [#86](https://github.com/pydantic/pydantic/pull/86)\ \ * **breaking change**: remove msgpack parsing [#201](https://github.com/pydantic/pydantic/pull/201)\ \ * add `FilePath` and `DirectoryPath` types [#10](https://github.com/pydantic/pydantic/pull/10)\ \ * model schema generation [#190](https://github.com/pydantic/pydantic/pull/190)\ \ * JSON serialization of models and schemas [#133](https://github.com/pydantic/pydantic/pull/133)\ \ \ v0.10.0 (2018-06-11)[¶](#v0100-2018-06-11 "Permanent link")\ \ ------------------------------------------------------------\ \ * add `Config.allow_population_by_alias` [#160](https://github.com/pydantic/pydantic/pull/160)\ , thanks [@bendemaree](https://github.com/bendemaree)\ \ * **breaking change**: new errors format [#179](https://github.com/pydantic/pydantic/pull/179)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * **breaking change**: removed `Config.min_number_size` and `Config.max_number_size` [#183](https://github.com/pydantic/pydantic/pull/183)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * **breaking change**: correct behaviour of `lt` and `gt` arguments to `conint` etc. [#188](https://github.com/pydantic/pydantic/pull/188)\ for the old behaviour use `le` and `ge` [#194](https://github.com/pydantic/pydantic/pull/194)\ , thanks [@jaheba](https://github.com/jaheba)\ \ * added error context and ability to redefine error message templates using `Config.error_msg_templates` [#183](https://github.com/pydantic/pydantic/pull/183)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * fix typo in validator exception [#150](https://github.com/pydantic/pydantic/pull/150)\ \ * copy defaults to model values, so different models don't share objects [#154](https://github.com/pydantic/pydantic/pull/154)\ \ \ v0.9.1 (2018-05-10)[¶](#v091-2018-05-10 "Permanent link")\ \ ----------------------------------------------------------\ \ * allow custom `get_field_config` on config classes [#159](https://github.com/pydantic/pydantic/pull/159)\ \ * add `UUID1`, `UUID3`, `UUID4` and `UUID5` types [#167](https://github.com/pydantic/pydantic/pull/167)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * modify some inconsistent docstrings and annotations [#173](https://github.com/pydantic/pydantic/pull/173)\ , thanks [@YannLuo](https://github.com/YannLuo)\ \ * fix type annotations for exotic types [#171](https://github.com/pydantic/pydantic/pull/171)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * Reuse type validators in exotic types [#171](https://github.com/pydantic/pydantic/pull/171)\ \ * scheduled monthly requirements updates [#168](https://github.com/pydantic/pydantic/pull/168)\ \ * add `Decimal`, `ConstrainedDecimal` and `condecimal` types [#170](https://github.com/pydantic/pydantic/pull/170)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ \ v0.9.0 (2018-04-28)[¶](#v090-2018-04-28 "Permanent link")\ \ ----------------------------------------------------------\ \ * tweak email-validator import error message [#145](https://github.com/pydantic/pydantic/pull/145)\ \ * fix parse error of `parse_date()` and `parse_datetime()` when input is 0 [#144](https://github.com/pydantic/pydantic/pull/144)\ , thanks [@YannLuo](https://github.com/YannLuo)\ \ * add `Config.anystr_strip_whitespace` and `strip_whitespace` kwarg to `constr`, by default values is `False` [#163](https://github.com/pydantic/pydantic/pull/163)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ * add `ConstrainedFloat`, `confloat`, `PositiveFloat` and `NegativeFloat` types [#166](https://github.com/pydantic/pydantic/pull/166)\ , thanks [@Gr1N](https://github.com/Gr1N)\ \ \ v0.8.0 (2018-03-25)[¶](#v080-2018-03-25 "Permanent link")\ \ ----------------------------------------------------------\ \ * fix type annotation for `inherit_config` [#139](https://github.com/pydantic/pydantic/pull/139)\ \ * **breaking change**: check for invalid field names in validators [#140](https://github.com/pydantic/pydantic/pull/140)\ \ * validate attributes of parent models [#141](https://github.com/pydantic/pydantic/pull/141)\ \ * **breaking change**: email validation now uses [email-validator](https://github.com/JoshData/python-email-validator)\ [#142](https://github.com/pydantic/pydantic/pull/142)\ \ \ v0.7.1 (2018-02-07)[¶](#v071-2018-02-07 "Permanent link")\ \ ----------------------------------------------------------\ \ * fix bug with `create_model` modifying the base class\ \ v0.7.0 (2018-02-06)[¶](#v070-2018-02-06 "Permanent link")\ \ ----------------------------------------------------------\ \ * added compatibility with abstract base classes (ABCs) [#123](https://github.com/pydantic/pydantic/pull/123)\ \ * add `create_model` method [#113](https://github.com/pydantic/pydantic/pull/113)\ [#125](https://github.com/pydantic/pydantic/pull/125)\ \ * **breaking change**: rename `.config` to `.__config__` on a model\ * **breaking change**: remove deprecated `.values()` on a model, use `.dict()` instead\ * remove use of `OrderedDict` and use simple dict [#126](https://github.com/pydantic/pydantic/pull/126)\ \ * add `Config.use_enum_values` [#127](https://github.com/pydantic/pydantic/pull/127)\ \ * add wildcard validators of the form `@validate('*')` [#128](https://github.com/pydantic/pydantic/pull/128)\ \ \ v0.6.4 (2018-02-01)[¶](#v064-2018-02-01 "Permanent link")\ \ ----------------------------------------------------------\ \ * allow Python date and times objects [#122](https://github.com/pydantic/pydantic/pull/122)\ \ \ v0.6.3 (2017-11-26)[¶](#v063-2017-11-26 "Permanent link")\ \ ----------------------------------------------------------\ \ * fix direct install without `README.rst` present\ \ v0.6.2 (2017-11-13)[¶](#v062-2017-11-13 "Permanent link")\ \ ----------------------------------------------------------\ \ * errors for invalid validator use\ * safer check for complex models in `Settings`\ \ v0.6.1 (2017-11-08)[¶](#v061-2017-11-08 "Permanent link")\ \ ----------------------------------------------------------\ \ * prevent duplicate validators, [#101](https://github.com/pydantic/pydantic/pull/101)\ \ * add `always` kwarg to validators, [#102](https://github.com/pydantic/pydantic/pull/102)\ \ \ v0.6.0 (2017-11-07)[¶](#v060-2017-11-07 "Permanent link")\ \ ----------------------------------------------------------\ \ * assignment validation [#94](https://github.com/pydantic/pydantic/pull/94)\ , thanks petroswork!\ * JSON in environment variables for complex types, [#96](https://github.com/pydantic/pydantic/pull/96)\ \ * add `validator` decorators for complex validation, [#97](https://github.com/pydantic/pydantic/pull/97)\ \ * depreciate `values(...)` and replace with `.dict(...)`, [#99](https://github.com/pydantic/pydantic/pull/99)\ \ \ v0.5.0 (2017-10-23)[¶](#v050-2017-10-23 "Permanent link")\ \ ----------------------------------------------------------\ \ * add `UUID` validation [#89](https://github.com/pydantic/pydantic/pull/89)\ \ * remove `index` and `track` from error object (json) if they're null [#90](https://github.com/pydantic/pydantic/pull/90)\ \ * improve the error text when a list is provided rather than a dict [#90](https://github.com/pydantic/pydantic/pull/90)\ \ * add benchmarks table to docs [#91](https://github.com/pydantic/pydantic/pull/91)\ \ \ v0.4.0 (2017-07-08)[¶](#v040-2017-07-08 "Permanent link")\ \ ----------------------------------------------------------\ \ * show length in string validation error\ * fix aliases in config during inheritance [#55](https://github.com/pydantic/pydantic/pull/55)\ \ * simplify error display\ * use unicode ellipsis in `truncate`\ * add `parse_obj`, `parse_raw` and `parse_file` helper functions [#58](https://github.com/pydantic/pydantic/pull/58)\ \ * switch annotation only fields to come first in fields list not last\ \ v0.3.0 (2017-06-21)[¶](#v030-2017-06-21 "Permanent link")\ \ ----------------------------------------------------------\ \ * immutable models via `config.allow_mutation = False`, associated cleanup and performance improvement [#44](https://github.com/pydantic/pydantic/pull/44)\ \ * immutable helper methods `construct()` and `copy()` [#53](https://github.com/pydantic/pydantic/pull/53)\ \ * allow pickling of models [#53](https://github.com/pydantic/pydantic/pull/53)\ \ * `setattr` is removed as `__setattr__` is now intelligent [#44](https://github.com/pydantic/pydantic/pull/44)\ \ * `raise_exception` removed, Models now always raise exceptions [#44](https://github.com/pydantic/pydantic/pull/44)\ \ * instance method validators removed\ * django-restful-framework benchmarks added [#47](https://github.com/pydantic/pydantic/pull/47)\ \ * fix inheritance bug [#49](https://github.com/pydantic/pydantic/pull/49)\ \ * make str type stricter so list, dict etc are not coerced to strings. [#52](https://github.com/pydantic/pydantic/pull/52)\ \ * add `StrictStr` which only always strings as input [#52](https://github.com/pydantic/pydantic/pull/52)\ \ \ v0.2.1 (2017-06-07)[¶](#v021-2017-06-07 "Permanent link")\ \ ----------------------------------------------------------\ \ * pypi and travis together messed up the deploy of `v0.2` this should fix it\ \ v0.2.0 (2017-06-07)[¶](#v020-2017-06-07 "Permanent link")\ \ ----------------------------------------------------------\ \ * **breaking change**: `values()` on a model is now a method not a property, takes `include` and `exclude` arguments\ * allow annotation only fields to support mypy\ * add pretty `to_string(pretty=True)` method for models\ \ v0.1.0 (2017-06-03)[¶](#v010-2017-06-03 "Permanent link")\ \ ----------------------------------------------------------\ \ * add docs\ * add history\ \ Was this page helpful?\ \ Thanks for your feedback!\ \ Thanks for your feedback!\ \ Back to top --- # Migration Guide - Pydantic Migration Guide =============== Pydantic V2 introduces a number of changes to the API, including some breaking changes. This page provides a guide highlighting the most important changes to help you migrate your code from Pydantic V1 to Pydantic V2. Install Pydantic V2[¶](#install-pydantic-v2 "Permanent link") -------------------------------------------------------------- Pydantic V2 is now the current production release of Pydantic. You can install Pydantic V2 from PyPI: `pip install -U pydantic` If you encounter any issues, please [create an issue in GitHub](https://github.com/pydantic/pydantic/issues) using the `bug V2` label. This will help us to actively monitor and track errors, and to continue to improve the library's performance. If you need to use latest Pydantic V1 for any reason, see the [Continue using Pydantic V1 features](#continue-using-pydantic-v1-features) section below for details on installation and imports from `pydantic.v1`. Code transformation tool[¶](#code-transformation-tool "Permanent link") ------------------------------------------------------------------------ We have created a tool to help you migrate your code. This tool is still in beta, but we hope it will help you to migrate your code more quickly. You can install the tool from PyPI: `pip install bump-pydantic` The usage is simple. If your project structure is: `* repo_folder * my_package * ...` Then you'll want to do: `cd /path/to/repo_folder bump-pydantic my_package` See more about it on the [Bump Pydantic](https://github.com/pydantic/bump-pydantic) repository. Continue using Pydantic V1 features[¶](#continue-using-pydantic-v1-features "Permanent link") ---------------------------------------------------------------------------------------------- Pydantic V1 is still available when you need it, though we recommend migrating to Pydantic V2 for its improvements and new features. If you need to use latest Pydantic V1, you can install it with: `pip install "pydantic==1.*"` The Pydantic V2 package also continues to provide access to the Pydantic V1 API by importing through `pydantic.v1`. For example, you can use the `BaseModel` class from Pydantic V1 instead of the Pydantic V2 `pydantic.BaseModel` class: `from pydantic.v1 import BaseModel` You can also import functions that have been removed from Pydantic V2, such as `lenient_isinstance`: `from pydantic.v1.utils import lenient_isinstance` Pydantic V1 documentation is available at [https://docs.pydantic.dev/1.10/](https://docs.pydantic.dev/1.10/) . ### Using Pydantic v1 features in a v1/v2 environment[¶](#using-pydantic-v1-features-in-a-v1v2-environment "Permanent link") As of `pydantic>=1.10.17`, the `pydantic.v1` namespace can be used within V1. This makes it easier to migrate to V2, which also supports the `pydantic.v1` namespace. In order to unpin a `pydantic<2` dependency and continue using V1 features, take the following steps: 1. Replace `pydantic<2` with `pydantic>=1.10.17` 2. Find and replace all occurrences of: `from pydantic. import ` with: `from pydantic.v1. import ` Here's how you can import `pydantic`'s v1 features based on your version of `pydantic`: `pydantic>=1.10.17,<3``pydantic<3` As of `v1.10.17` the `.v1` namespace is available in V1, allowing imports as below: `from pydantic.v1.fields import ModelField` All versions of Pydantic V1 and V2 support the following import pattern, in case you don't know which version of Pydantic you are using: `try: from pydantic.v1.fields import ModelField except ImportError: from pydantic.fields import ModelField` Note When importing modules using `pydantic>=1.10.17,<2` with the `.v1` namespace these modules will _not_ be the **same** module as the same import without the `.v1` namespace, but the symbols imported _will_ be. For example `pydantic.v1.fields is not pydantic.fields` but `pydantic.v1.fields.ModelField is pydantic.fields.ModelField`. Luckily, this is not likely to be relevant in the vast majority of cases. It's just an unfortunate consequence of providing a smoother migration experience. Migration guide[¶](#migration-guide "Permanent link") ------------------------------------------------------ The following sections provide details on the most important changes in Pydantic V2. ### Changes to `pydantic.BaseModel`[¶](#changes-to-pydanticbasemodel "Permanent link") Various method names have been changed; all non-deprecated `BaseModel` methods now have names matching either the format `model_.*` or `__.*pydantic.*__`. Where possible, we have retained the deprecated methods with their old names to help ease migration, but calling them will emit `DeprecationWarning`s. | Pydantic V1 | Pydantic V2 | | --- | --- | | `__fields__` | `model_fields` | | `__private_attributes__` | `__pydantic_private__` | | `__validators__` | `__pydantic_validator__` | | `construct()` | `model_construct()` | | `copy()` | `model_copy()` | | `dict()` | `model_dump()` | | `json_schema()` | `model_json_schema()` | | `json()` | `model_dump_json()` | | `parse_obj()` | `model_validate()` | | `update_forward_refs()` | `model_rebuild()` | * Some of the built-in data-loading functionality has been slated for removal. In particular, `parse_raw` and `parse_file` are now deprecated. In Pydantic V2, `model_validate_json` works like `parse_raw`. Otherwise, you should load the data and then pass it to `model_validate`. * The `from_orm` method has been deprecated; you can now just use `model_validate` (equivalent to `parse_obj` from Pydantic V1) to achieve something similar, as long as you've set `from_attributes=True` in the model config. * The `__eq__` method has changed for models. * Models can only be equal to other `BaseModel` instances. * For two model instances to be equal, they must have the same: * Type (or, in the case of generic models, non-parametrized generic origin type) * Field values * Extra values (only relevant when `model_config['extra'] == 'allow'`) * Private attribute values; models with different values of private attributes are no longer equal. * Models are no longer equal to the dicts containing their data. * Non-generic models of different types are never equal. * Generic models with different origin types are never equal. We don't require _exact_ type equality so that, for example, instances of `MyGenericModel[Any]` could be equal to instances of `MyGenericModel[int]`. * We have replaced the use of the `__root__` field to specify a "custom root model" with a new type called [`RootModel`](../concepts/models/#rootmodel-and-custom-root-types) which is intended to replace the functionality of using a field called `__root__` in Pydantic V1. Note, `RootModel` types no longer support the `arbitrary_types_allowed` config setting. See [this issue comment](https://github.com/pydantic/pydantic/issues/6710#issuecomment-1700948167) for an explanation. * We have significantly expanded Pydantic's capabilities related to customizing serialization. In particular, we have added the [`@field_serializer`](../api/functional_serializers/#pydantic.functional_serializers.field_serializer) , [`@model_serializer`](../api/functional_serializers/#pydantic.functional_serializers.model_serializer) , and [`@computed_field`](../api/fields/#pydantic.fields.computed_field) decorators, which each address various shortcomings from Pydantic V1. * See [Custom serializers](../concepts/serialization/#custom-serializers) for the usage docs of these new decorators. * Due to performance overhead and implementation complexity, we have now deprecated support for specifying `json_encoders` in the model config. This functionality was originally added for the purpose of achieving custom serialization logic, and we think the new serialization decorators are a better choice in most common scenarios. * We have changed the behavior related to serializing subclasses of models when they occur as nested fields in a parent model. In V1, we would always include all fields from the subclass instance. In V2, when we dump a model, we only include the fields that are defined on the annotated type of the field. This helps prevent some accidental security bugs. You can read more about this (including how to opt out of this behavior) in the [Subclass instances for fields of BaseModel, dataclasses, TypedDict](../concepts/serialization/#subclass-instances-for-fields-of-basemodel-dataclasses-typeddict) section of the model exporting docs. * `GetterDict` has been removed as it was just an implementation detail of `orm_mode`, which has been removed. * In many cases, arguments passed to the constructor will be **copied** in order to perform validation and, where necessary, coercion. This is notable in the case of passing mutable objects as arguments to a constructor. You can see an example + more detail [here](https://docs.pydantic.dev/latest/concepts/models/#attribute-copies) . * The `.json()` method is deprecated, and attempting to use this deprecated method with arguments such as `indent` or `ensure_ascii` may lead to confusing errors. For best results, switch to V2's equivalent, `model_dump_json()`. If you'd still like to use said arguments, you can use [this workaround](https://github.com/pydantic/pydantic/issues/8825#issuecomment-1946206415) . * JSON serialization of non-string key values is generally done with `str(key)`, leading to some changes in behavior such as the following: `from typing import Optional from pydantic import BaseModel as V2BaseModel from pydantic.v1 import BaseModel as V1BaseModel class V1Model(V1BaseModel): a: dict[Optional[str], int] class V2Model(V2BaseModel): a: dict[Optional[str], int] v1_model = V1Model(a={None: 123}) v2_model = V2Model(a={None: 123}) # V1 print(v1_model.json()) #> {"a": {"null": 123}} # V2 print(v2_model.model_dump_json()) #> {"a":{"None":123}}` * `model_dump_json()` results are compacted in order to save space, and don't always exactly match that of `json.dumps()` output. That being said, you can easily modify the separators used in `json.dumps()` results in order to align the two outputs: `import json from pydantic import BaseModel as V2BaseModel from pydantic.v1 import BaseModel as V1BaseModel class V1Model(V1BaseModel): a: list[str] class V2Model(V2BaseModel): a: list[str] v1_model = V1Model(a=['fancy', 'sushi']) v2_model = V2Model(a=['fancy', 'sushi']) # V1 print(v1_model.json()) #> {"a": ["fancy", "sushi"]} # V2 print(v2_model.model_dump_json()) #> {"a":["fancy","sushi"]} # Plain json.dumps print(json.dumps(v2_model.model_dump())) #> {"a": ["fancy", "sushi"]} # Modified json.dumps print(json.dumps(v2_model.model_dump(), separators=(',', ':'))) #> {"a":["fancy","sushi"]}` ### Changes to `pydantic.generics.GenericModel`[¶](#changes-to-pydanticgenericsgenericmodel "Permanent link") The `pydantic.generics.GenericModel` class is no longer necessary, and has been removed. Instead, you can now create generic `BaseModel` subclasses by just adding `Generic` as a parent class on a `BaseModel` subclass directly. This looks like `class MyGenericModel(BaseModel, Generic[T]): ...`. Mixing of V1 and V2 models is not supported which means that type parameters of such generic `BaseModel` (V2) cannot be V1 models. While it may not raise an error, we strongly advise against using _parametrized_ generics in `isinstance` checks. * For example, you should not do `isinstance(my_model, MyGenericModel[int])`. However, it is fine to do `isinstance(my_model, MyGenericModel)`. (Note that for standard generics, it would raise an error to do a subclass check with a parameterized generic.) * If you need to perform `isinstance` checks against parametrized generics, you can do this by subclassing the parametrized generic class. This looks like `class MyIntModel(MyGenericModel[int]): ...` and `isinstance(my_model, MyIntModel)`. Find more information in the [Generic models](../concepts/models/#generic-models) documentation. ### Changes to `pydantic.Field`[¶](#changes-to-pydanticfield "Permanent link") `Field` no longer supports arbitrary keyword arguments to be added to the JSON schema. Instead, any extra data you want to add to the JSON schema should be passed as a dictionary to the `json_schema_extra` keyword argument. In Pydantic V1, the `alias` property returns the field's name when no alias is set. In Pydantic V2, this behavior has changed to return `None` when no alias is set. The following properties have been removed from or changed in `Field`: * `const` * `min_items` (use `min_length` instead) * `max_items` (use `max_length` instead) * `unique_items` * `allow_mutation` (use `frozen` instead) * `regex` (use `pattern` instead) * `final` (use the [typing.Final](https://docs.python.org/3/library/typing.html#typing.Final) type hint instead) Field constraints are no longer automatically pushed down to the parameters of generics. For example, you can no longer validate every element of a list matches a regex by providing `my_list: list[str] = Field(pattern=".*")`. Instead, use [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) to provide an annotation on the `str` itself: `my_list: list[Annotated[str, Field(pattern=".*")]]` ### Changes to dataclasses[¶](#changes-to-dataclasses "Permanent link") Pydantic [dataclasses](../concepts/dataclasses/) continue to be useful for enabling the data validation on standard dataclasses without having to subclass `BaseModel`. Pydantic V2 introduces the following changes to this dataclass behavior: * When used as fields, dataclasses (Pydantic or vanilla) no longer accept tuples as validation inputs; dicts should be used instead. * The `__post_init__` in Pydantic dataclasses will now be called _after_ validation, rather than before. * As a result, the `__post_init_post_parse__` method would have become redundant, so has been removed. * Pydantic no longer supports `extra='allow'` for Pydantic dataclasses, where extra fields passed to the initializer would be stored as extra attributes on the dataclass. `extra='ignore'` is still supported for the purpose of ignoring unexpected fields while parsing data, they just won't be stored on the instance. * Pydantic dataclasses no longer have an attribute `__pydantic_model__`, and no longer use an underlying `BaseModel` to perform validation or provide other functionality. * To perform validation, generate a JSON schema, or make use of any other functionality that may have required `__pydantic_model__` in V1, you should now wrap the dataclass with a [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) ([discussed more below](#introduction-of-typeadapter) ) and make use of its methods. * In Pydantic V1, if you used a vanilla (i.e., non-Pydantic) dataclass as a field, the config of the parent type would be used as though it was the config for the dataclass itself as well. In Pydantic V2, this is no longer the case. * In Pydantic V2, to override the config (like you would with `model_config` on a `BaseModel`), you can use the `config` parameter on the `@dataclass` decorator. See [Dataclass Config](../concepts/dataclasses/#dataclass-config) for examples. ### Changes to config[¶](#changes-to-config "Permanent link") * In Pydantic V2, to specify config on a model, you should set a class attribute called `model_config` to be a dict with the key/value pairs you want to be used as the config. The Pydantic V1 behavior to create a class called `Config` in the namespace of the parent `BaseModel` subclass is now deprecated. * When subclassing a model, the `model_config` attribute is inherited. This is helpful in the case where you'd like to use a base class with a given configuration for many models. Note, if you inherit from multiple `BaseModel` subclasses, like `class MyModel(Model1, Model2)`, the non-default settings in the `model_config` attribute from the two models will be merged, and for any settings defined in both, those from `Model2` will override those from `Model1`. * The following config settings have been removed: * `allow_mutation` — this has been removed. You should be able to use [frozen](../api/config/#pydantic.config.ConfigDict) equivalently (inverse of current use). * `error_msg_templates` * `fields` — this was the source of various bugs, so has been removed. You should be able to use `Annotated` on fields to modify them as desired. * `getter_dict` — `orm_mode` has been removed, and this implementation detail is no longer necessary. * `smart_union` - the default `union_mode` in Pydantic V2 is `'smart'`. * `underscore_attrs_are_private` — the Pydantic V2 behavior is now the same as if this was always set to `True` in Pydantic V1. * `json_loads` * `json_dumps` * `copy_on_model_validation` * `post_init_call` * The following config settings have been renamed: * `allow_population_by_field_name` → `populate_by_name` (or `validate_by_name` starting in v2.11) * `anystr_lower` → `str_to_lower` * `anystr_strip_whitespace` → `str_strip_whitespace` * `anystr_upper` → `str_to_upper` * `keep_untouched` → `ignored_types` * `max_anystr_length` → `str_max_length` * `min_anystr_length` → `str_min_length` * `orm_mode` → `from_attributes` * `schema_extra` → `json_schema_extra` * `validate_all` → `validate_default` See the [`ConfigDict` API reference](../api/config/#pydantic.config.ConfigDict) for more details. ### Changes to validators[¶](#changes-to-validators "Permanent link") #### `@validator` and `@root_validator` are deprecated[¶](#validator-and-root_validator-are-deprecated "Permanent link") * `@validator` has been deprecated, and should be replaced with [`@field_validator`](../concepts/validators/) , which provides various new features and improvements. * The new `@field_validator` decorator does not have the `each_item` keyword argument; validators you want to apply to items within a generic container should be added by annotating the type argument. See [validators in Annotated metadata](../concepts/types/#using-the-annotated-pattern) for details. This looks like `list[Annotated[int, Field(ge=0)]]` * Even if you keep using the deprecated `@validator` decorator, you can no longer add the `field` or `config` arguments to the signature of validator functions. If you need access to these, you'll need to migrate to `@field_validator` — see the [next section](#changes-to-validators-allowed-signatures) for more details. * If you use the `always=True` keyword argument to a validator function, note that standard validators for the annotated type will _also_ be applied even to defaults, not just the custom validators. For example, despite the fact that the validator below will never error, the following code raises a `ValidationError`: Note To avoid this, you can use the `validate_default` argument in the `Field` function. When set to `True`, it mimics the behavior of `always=True` in Pydantic v1. However, the new way of using `validate_default` is encouraged as it provides more flexibility and control. `from pydantic import BaseModel, validator class Model(BaseModel): x: str = 1 @validator('x', always=True) @classmethod def validate_x(cls, v): return v Model()` * `@root_validator` has been deprecated, and should be replaced with [`@model_validator`](../api/functional_validators/#pydantic.functional_validators.model_validator) , which also provides new features and improvements. * Under some circumstances (such as assignment when `model_config['validate_assignment'] is True`), the `@model_validator` decorator will receive an instance of the model, not a dict of values. You may need to be careful to handle this case. * Even if you keep using the deprecated `@root_validator` decorator, due to refactors in validation logic, you can no longer run with `skip_on_failure=False` (which is the default value of this keyword argument, so must be set explicitly to `True`). #### Changes to `@validator`'s allowed signatures[¶](#changes-to-validators-allowed-signatures "Permanent link") In Pydantic V1, functions wrapped by `@validator` could receive keyword arguments with metadata about what was being validated. Some of these arguments have been removed from `@field_validator` in Pydantic V2: * `config`: Pydantic V2's config is now a dictionary instead of a class, which means this argument is no longer backwards compatible. If you need to access the configuration you should migrate to `@field_validator` and use `info.config`. * `field`: this argument used to be a `ModelField` object, which was a quasi-internal class that no longer exists in Pydantic V2. Most of this information can still be accessed by using the field name from `info.field_name` to index into `cls.model_fields` `from pydantic import BaseModel, ValidationInfo, field_validator class Model(BaseModel): x: int @field_validator('x') def val_x(cls, v: int, info: ValidationInfo) -> int: assert info.config is not None print(info.config.get('title')) #> Model print(cls.model_fields[info.field_name].is_required()) #> True return v Model(x=1)` #### `TypeError` is no longer converted to `ValidationError` in validators[¶](#typeerror-is-no-longer-converted-to-validationerror-in-validators "Permanent link") Previously, when raising a `TypeError` within a validator function, that error would be wrapped into a `ValidationError` and, in some cases (such as with FastAPI), these errors might be displayed to end users. This led to a variety of undesirable behavior — for example, calling a function with the wrong signature might produce a user-facing `ValidationError`. However, in Pydantic V2, when a `TypeError` is raised in a validator, it is no longer converted into a `ValidationError`: `import pytest from pydantic import BaseModel, field_validator # or validator class Model(BaseModel): x: int @field_validator('x') def val_x(cls, v: int) -> int: return str.lower(v) # raises a TypeError with pytest.raises(TypeError): Model(x=1)` This applies to all validation decorators. #### Validator behavior changes[¶](#validator-behavior-changes "Permanent link") Pydantic V2 includes some changes to type coercion. For example: * coercing `int`, `float`, and `Decimal` values to strings is now optional and disabled by default, see [Coerce Numbers to Strings](../api/config/#pydantic.config.ConfigDict.coerce_numbers_to_str) . * iterable of pairs is no longer coerced to a dict. See the [Conversion table](../concepts/conversion_table/) for details on Pydantic V2 type coercion defaults. #### The `allow_reuse` keyword argument is no longer necessary[¶](#the-allow_reuse-keyword-argument-is-no-longer-necessary "Permanent link") Previously, Pydantic tracked "reused" functions in decorators as this was a common source of mistakes. We did this by comparing the function's fully qualified name (module name + function name), which could result in false positives. The `allow_reuse` keyword argument could be used to disable this when it was intentional. Our approach to detecting repeatedly defined functions has been overhauled to only error for redefinition within a single class, reducing false positives and bringing the behavior more in line with the errors that type checkers and linters would give for defining a method with the same name multiple times in a single class definition. In nearly all cases, if you were using `allow_reuse=True`, you should be able to simply delete that keyword argument and have things keep working as expected. #### `@validate_arguments` has been renamed to `@validate_call`[¶](#validate_arguments-has-been-renamed-to-validate_call "Permanent link") In Pydantic V2, the `@validate_arguments` decorator has been renamed to `@validate_call`. In Pydantic V1, the decorated function had various attributes added, such as `raw_function`, and `validate` (which could be used to validate arguments without actually calling the decorated function). Due to limited use of these attributes, and performance-oriented changes in implementation, we have not preserved this functionality in `@validate_call`. ### Input types are not preserved[¶](#input-types-are-not-preserved "Permanent link") In Pydantic V1 we made great efforts to preserve the types of all field inputs for generic collections when they were proper subtypes of the field annotations. For example, given the annotation `Mapping[str, int]` if you passed in a `collection.Counter()` you'd get a `collection.Counter()` as the value. Supporting this behavior in V2 would have negative performance implications for the general case (we'd have to check types every time) and would add a lot of complexity to validation. Further, even in V1 this behavior was inconsistent and partially broken: it did not work for many types (`str`, `UUID`, etc.), and for generic collections it's impossible to re-build the original input correctly without a lot of special casing (consider `ChainMap`; rebuilding the input is necessary because we need to replace values after validation, e.g. if coercing strings to ints). In Pydantic V2 we no longer attempt to preserve the input type in all cases; instead, we only promise that the output type will match the type annotations. Going back to the `Mapping` example, we promise the output will be a valid `Mapping`, and in practice it will be a plain `dict`: Python 3.9 and abovePython 3.10 and above `from typing import Mapping from pydantic import TypeAdapter class MyDict(dict): pass ta = TypeAdapter(Mapping[str, int]) v = ta.validate_python(MyDict()) print(type(v)) #> ` `from collections.abc import Mapping from pydantic import TypeAdapter class MyDict(dict): pass ta = TypeAdapter(Mapping[str, int]) v = ta.validate_python(MyDict()) print(type(v)) #> ` If you want the output type to be a specific type, consider annotating it as such or implementing a custom validator: Python 3.9 and abovePython 3.10 and above `from typing import Annotated, Any, Mapping, TypeVar from pydantic import ( TypeAdapter, ValidationInfo, ValidatorFunctionWrapHandler, WrapValidator, ) def restore_input_type( value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo ) -> Any: return type(value)(handler(value)) T = TypeVar('T') PreserveType = Annotated[T, WrapValidator(restore_input_type)] ta = TypeAdapter(PreserveType[Mapping[str, int]]) class MyDict(dict): pass v = ta.validate_python(MyDict()) assert type(v) is MyDict` `from typing import Annotated, Any, TypeVar from collections.abc import Mapping from pydantic import ( TypeAdapter, ValidationInfo, ValidatorFunctionWrapHandler, WrapValidator, ) def restore_input_type( value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo ) -> Any: return type(value)(handler(value)) T = TypeVar('T') PreserveType = Annotated[T, WrapValidator(restore_input_type)] ta = TypeAdapter(PreserveType[Mapping[str, int]]) class MyDict(dict): pass v = ta.validate_python(MyDict()) assert type(v) is MyDict` While we don't promise to preserve input types everywhere, we _do_ preserve them for subclasses of `BaseModel`, and for dataclasses: `import pydantic.dataclasses from pydantic import BaseModel class InnerModel(BaseModel): x: int class OuterModel(BaseModel): inner: InnerModel class SubInnerModel(InnerModel): y: int m = OuterModel(inner=SubInnerModel(x=1, y=2)) print(m) #> inner=SubInnerModel(x=1, y=2) @pydantic.dataclasses.dataclass class InnerDataclass: x: int @pydantic.dataclasses.dataclass class SubInnerDataclass(InnerDataclass): y: int @pydantic.dataclasses.dataclass class OuterDataclass: inner: InnerDataclass d = OuterDataclass(inner=SubInnerDataclass(x=1, y=2)) print(d) #> OuterDataclass(inner=SubInnerDataclass(x=1, y=2))` ### Changes to Handling of Standard Types[¶](#changes-to-handling-of-standard-types "Permanent link") #### Dicts[¶](#dicts "Permanent link") Iterables of pairs (which include empty iterables) no longer pass validation for fields of type `dict`. #### Unions[¶](#unions "Permanent link") While union types will still attempt validation of each choice from left to right, they now preserve the type of the input whenever possible, even if the correct type is not the first choice for which the input would pass validation. As a demonstration, consider the following example: Python 3.9 and abovePython 3.10 and above `from typing import Union from pydantic import BaseModel class Model(BaseModel): x: Union[int, str] print(Model(x='1')) #> x='1'` `from pydantic import BaseModel class Model(BaseModel): x: int | str print(Model(x='1')) #> x='1'` In Pydantic V1, the printed result would have been `x=1`, since the value would pass validation as an `int`. In Pydantic V2, we recognize that the value is an instance of one of the cases and short-circuit the standard union validation. To revert to the non-short-circuiting left-to-right behavior of V1, annotate the union with `Field(union_mode='left_to_right')`. See [Union Mode](../concepts/unions/#union-modes) for more details. #### Required, optional, and nullable fields[¶](#required-optional-and-nullable-fields "Permanent link") Pydantic V2 changes some of the logic for specifying whether a field annotated as `Optional` is required (i.e., has no default value) or not (i.e., has a default value of `None` or any other value of the corresponding type), and now more closely matches the behavior of `dataclasses`. Similarly, fields annotated as `Any` no longer have a default value of `None`. The following table describes the behavior of field annotations in V2: | State | Field Definition | | --- | --- | | Required, cannot be `None` | `f1: str` | | Not required, cannot be `None`, is `'abc'` by default | `f2: str = 'abc'` | | Required, can be `None` | `f3: Optional[str]` | | Not required, can be `None`, is `None` by default | `f4: Optional[str] = None` | | Not required, can be `None`, is `'abc'` by default | `f5: Optional[str] = 'abc'` | | Required, can be any type (including `None`) | `f6: Any` | | Not required, can be any type (including `None`) | `f7: Any = None` | Note A field annotated as `typing.Optional[T]` will be required, and will allow for a value of `None`. It does not mean that the field has a default value of `None`. _(This is a breaking change from V1.)_ Note Any default value if provided makes a field not required. Here is a code example demonstrating the above: Python 3.9 and abovePython 3.10 and above `from typing import Optional from pydantic import BaseModel, ValidationError class Foo(BaseModel): f1: str # required, cannot be None f2: Optional[str] # required, can be None - same as str | None f3: Optional[str] = None # not required, can be None f4: str = 'Foobar' # not required, but cannot be None try: Foo(f1=None, f2=None, f4='b') except ValidationError as e: print(e) """ 1 validation error for Foo f1 Input should be a valid string [type=string_type, input_value=None, input_type=NoneType] """` `from pydantic import BaseModel, ValidationError class Foo(BaseModel): f1: str # required, cannot be None f2: str | None # required, can be None - same as str | None f3: str | None = None # not required, can be None f4: str = 'Foobar' # not required, but cannot be None try: Foo(f1=None, f2=None, f4='b') except ValidationError as e: print(e) """ 1 validation error for Foo f1 Input should be a valid string [type=string_type, input_value=None, input_type=NoneType] """` #### Patterns / regex on strings[¶](#patterns-regex-on-strings "Permanent link") Pydantic V1 used Python's regex library. Pydantic V2 uses the Rust [regex crate](https://github.com/rust-lang/regex) . This crate is not just a "Rust version of regular expressions", it's a completely different approach to regular expressions. In particular, it promises linear time searching of strings in exchange for dropping a couple of features (namely look arounds and backreferences). We believe this is a tradeoff worth making, in particular because Pydantic is used to validate untrusted input where ensuring things don't accidentally run in exponential time depending on the untrusted input is important. On the flipside, for anyone not using these features complex regex validation should be orders of magnitude faster because it's done in Rust and in linear time. If you still want to use Python's regex library, you can use the [`regex_engine`](../api/config/#pydantic.config.ConfigDict.regex_engine) config setting. ### Type conversion from floats to integers[¶](#type-conversion-from-floats-to-integers "Permanent link") In V1, whenever a field was annotated as `int`, any float value would be accepted, which could lead to a potential data loss if the float value contains a non-zero decimal part. In V2, type conversion from floats to integers is only allowed if the decimal part is zero: `from pydantic import BaseModel, ValidationError class Model(BaseModel): x: int print(Model(x=10.0)) #> x=10 try: Model(x=10.2) except ValidationError as err: print(err) """ 1 validation error for Model x Input should be a valid integer, got a number with a fractional part [type=int_from_float, input_value=10.2, input_type=float] """` ### Introduction of `TypeAdapter`[¶](#introduction-of-typeadapter "Permanent link") Pydantic V1 had weak support for validating or serializing non-`BaseModel` types. To work with them, you had to either create a "root" model or use the utility functions in `pydantic.tools` (namely, `parse_obj_as` and `schema_of`). In Pydantic V2 this is _a lot_ easier: the [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) class lets you create an object with methods for validating, serializing, and producing JSON schemas for arbitrary types. This serves as a complete replacement for `parse_obj_as` and `schema_of` (which are now deprecated), and also covers some of the use cases of "root" models. ([`RootModel`](../concepts/models/#rootmodel-and-custom-root-types) , [discussed above](#changes-to-pydanticbasemodel) , covers the others.) `from pydantic import TypeAdapter adapter = TypeAdapter(list[int]) assert adapter.validate_python(['1', '2', '3']) == [1, 2, 3] print(adapter.json_schema()) #> {'items': {'type': 'integer'}, 'type': 'array'}` Due to limitations of inferring generic types with common type checkers, to get proper typing in some scenarios, you may need to explicitly specify the generic parameter: `from pydantic import TypeAdapter adapter = TypeAdapter[str | int](str | int) ...` See [Type Adapter](../concepts/type_adapter/) for more information. ### Defining custom types[¶](#defining-custom-types "Permanent link") We have completely overhauled the way custom types are defined in pydantic. We have exposed hooks for generating both `pydantic-core` and JSON schemas, allowing you to get all the performance benefits of Pydantic V2 even when using your own custom types. We have also introduced ways to use [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) to add custom validation to your own types. The main changes are: * `__get_validators__` should be replaced with `__get_pydantic_core_schema__`. See [Custom Data Types](../concepts/types/#customizing_validation_with_get_pydantic_core_schema) for more information. * `__modify_schema__` becomes `__get_pydantic_json_schema__`. See [JSON Schema Customization](../concepts/json_schema/#customizing-json-schema) for more information. Additionally, you can use [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) to modify or provide the `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__` functions of a type by annotating it, rather than modifying the type itself. This provides a powerful and flexible mechanism for integrating third-party types with Pydantic, and in some cases may help you remove hacks from Pydantic V1 introduced to work around the limitations for custom types. See [Custom Data Types](../concepts/types/#custom-types) for more information. ### Changes to JSON schema generation[¶](#changes-to-json-schema-generation "Permanent link") We received many requests over the years to make changes to the JSON schemas that pydantic generates. In Pydantic V2, we have tried to address many of the common requests: * The JSON schema for `Optional` fields now indicates that the value `null` is allowed. * The `Decimal` type is now exposed in JSON schema (and serialized) as a string. * The JSON schema no longer preserves namedtuples as namedtuples. * The JSON schema we generate by default now targets draft 2020-12 (with some OpenAPI extensions). * When they differ, you can now specify if you want the JSON schema representing the inputs to validation, or the outputs from serialization. However, there have been many reasonable requests over the years for changes which we have not chosen to implement. In Pydantic V1, even if you were willing to implement changes yourself, it was very difficult because the JSON schema generation process involved various recursive function calls; to override one, you'd have to copy and modify the whole implementation. In Pydantic V2, one of our design goals was to make it easier to customize JSON schema generation. To this end, we have introduced the class [`GenerateJsonSchema`](../api/json_schema/#pydantic.json_schema.GenerateJsonSchema) , which implements the translation of a type's pydantic-core schema into a JSON schema. By design, this class breaks the JSON schema generation process into smaller methods that can be easily overridden in subclasses to modify the "global" approach to generating JSON schema. The various methods that can be used to produce JSON schema (such as `BaseModel.model_json_schema` or `TypeAdapter.json_schema`) accept a keyword argument `schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema`, and you can pass your custom subclass to these methods in order to use your own approach to generating JSON schema. Hopefully this means that if you disagree with any of the choices we've made, or if you are reliant on behaviors in Pydantic V1 that have changed in Pydantic V2, you can use a custom `schema_generator`, modifying the `GenerateJsonSchema` class as necessary for your application. ### `BaseSettings` has moved to `pydantic-settings`[¶](#basesettings-has-moved-to-pydantic-settings "Permanent link") [`BaseSettings`](../api/pydantic_settings/#pydantic_settings.BaseSettings) , the base object for Pydantic [settings management](../concepts/pydantic_settings/) , has been moved to a separate package, [`pydantic-settings`](https://github.com/pydantic/pydantic-settings) . Also, the `parse_env_var` classmethod has been removed. So, you need to [customise settings sources](../concepts/pydantic_settings/#customise-settings-sources) to have your own parsing function. ### Color and Payment Card Numbers moved to `pydantic-extra-types`[¶](#color-and-payment-card-numbers-moved-to-pydantic-extra-types "Permanent link") The following special-use types have been moved to the [Pydantic Extra Types](https://github.com/pydantic/pydantic-extra-types) package, which may be installed separately if needed. * [Color Types](../api/pydantic_extra_types_color/) * [Payment Card Numbers](../api/pydantic_extra_types_payment/) ### Url and Dsn types in `pydantic.networks` no longer inherit from `str`[¶](#url-and-dsn-types-in-pydanticnetworks-no-longer-inherit-from-str "Permanent link") In Pydantic V1 the [`AnyUrl`](../api/networks/#pydantic.networks.AnyUrl) type inherited from `str`, and all the other `Url` and `Dsn` types inherited from these. In Pydantic V2 these types are built on two new `Url` and `MultiHostUrl` classes using `Annotated`. Inheriting from `str` had upsides and downsides, and for V2 we decided it would be better to remove this. To use these types in APIs which expect `str` you'll now need to convert them (with `str(url)`). Pydantic V2 uses Rust's [Url](https://crates.io/crates/url) crate for URL validation. Some of the URL validation differs slightly from the previous behavior in V1. One notable difference is that the new `Url` types append slashes to the validated version if no path is included, even if a slash is not specified in the argument to a `Url` type constructor. See the example below for this behavior: `from pydantic import AnyUrl assert str(AnyUrl(url='https://google.com')) == 'https://google.com/' assert str(AnyUrl(url='https://google.com/')) == 'https://google.com/' assert str(AnyUrl(url='https://google.com/api')) == 'https://google.com/api' assert str(AnyUrl(url='https://google.com/api/')) == 'https://google.com/api/'` If you still want to use the old behavior without the appended slash, take a look at this [solution](https://github.com/pydantic/pydantic/issues/7186#issuecomment-1690235887) . ### Constrained types[¶](#constrained-types "Permanent link") The `Constrained*` classes were _removed_, and you should replace them by `Annotated[, Field(...)]`, for example: `from pydantic import BaseModel, ConstrainedInt class MyInt(ConstrainedInt): ge = 0 class Model(BaseModel): x: MyInt` ...becomes: `from typing import Annotated from pydantic import BaseModel, Field MyInt = Annotated[int, Field(ge=0)] class Model(BaseModel): x: MyInt` Read more about it in the [Composing types via `Annotated`](../concepts/types/#using-the-annotated-pattern) docs. For `ConstrainedStr` you can use [`StringConstraints`](../api/types/#pydantic.types.StringConstraints) instead. ### Mypy plugins[¶](#mypy-plugins "Permanent link") Pydantic V2 contains a [mypy](https://mypy.readthedocs.io/en/stable/extending_mypy.html#configuring-mypy-to-use-plugins) plugin in `pydantic.mypy`. When using [V1 features](./#continue-using-pydantic-v1-features) the `pydantic.v1.mypy` plugin might need to also be enabled. To configure the mypy plugins: `mypy.ini``pyproject.toml` ``[mypy] plugins = pydantic.mypy, pydantic.v1.mypy # include `.v1.mypy` if required.`` ``[tool.mypy] plugins = [ "pydantic.mypy", "pydantic.v1.mypy", # include `.v1.mypy` if required. ]`` Other changes[¶](#other-changes "Permanent link") -------------------------------------------------- * Dropped support for [`email-validator<2.0.0`](https://github.com/JoshData/python-email-validator) . Make sure to update using `pip install -U email-validator`. Moved in Pydantic V2[¶](#moved-in-pydantic-v2 "Permanent link") ---------------------------------------------------------------- | Pydantic V1 | Pydantic V2 | | --- | --- | | `pydantic.BaseSettings` | [`pydantic_settings.BaseSettings`](#basesettings-has-moved-to-pydantic-settings) | | `pydantic.color` | [`pydantic_extra_types.color`](../api/pydantic_extra_types_color/#pydantic_extra_types.color) | | `pydantic.types.PaymentCardBrand` | [`pydantic_extra_types.PaymentCardBrand`](#color-and-payment-card-numbers-moved-to-pydantic-extra-types) | | `pydantic.types.PaymentCardNumber` | [`pydantic_extra_types.PaymentCardNumber`](#color-and-payment-card-numbers-moved-to-pydantic-extra-types) | | `pydantic.utils.version_info` | [`pydantic.version.version_info`](../api/version/#pydantic.version.version_info) | | `pydantic.error_wrappers.ValidationError` | [`pydantic.ValidationError`](../api/pydantic_core/#pydantic_core.ValidationError) | | `pydantic.utils.to_camel` | [`pydantic.alias_generators.to_pascal`](../api/config/#pydantic.alias_generators.to_pascal) | | `pydantic.utils.to_lower_camel` | [`pydantic.alias_generators.to_camel`](../api/config/#pydantic.alias_generators.to_camel) | | `pydantic.PyObject` | [`pydantic.ImportString`](../api/types/#pydantic.types.ImportString) | Deprecated and moved in Pydantic V2[¶](#deprecated-and-moved-in-pydantic-v2 "Permanent link") ---------------------------------------------------------------------------------------------- | Pydantic V1 | Pydantic V2 | | --- | --- | | `pydantic.tools.schema_of` | `pydantic.deprecated.tools.schema_of` | | `pydantic.tools.parse_obj_as` | `pydantic.deprecated.tools.parse_obj_as` | | `pydantic.tools.schema_json_of` | `pydantic.deprecated.tools.schema_json_of` | | `pydantic.json.pydantic_encoder` | `pydantic.deprecated.json.pydantic_encoder` | | `pydantic.validate_arguments` | `pydantic.deprecated.decorator.validate_arguments` | | `pydantic.json.custom_pydantic_encoder` | `pydantic.deprecated.json.custom_pydantic_encoder` | | `pydantic.json.ENCODERS_BY_TYPE` | `pydantic.deprecated.json.ENCODERS_BY_TYPE` | | `pydantic.json.timedelta_isoformat` | `pydantic.deprecated.json.timedelta_isoformat` | | `pydantic.decorator.validate_arguments` | `pydantic.deprecated.decorator.validate_arguments` | | `pydantic.class_validators.validator` | `pydantic.deprecated.class_validators.validator` | | `pydantic.class_validators.root_validator` | `pydantic.deprecated.class_validators.root_validator` | | `pydantic.utils.deep_update` | `pydantic.v1.utils.deep_update` | | `pydantic.utils.GetterDict` | `pydantic.v1.utils.GetterDict` | | `pydantic.utils.lenient_issubclass` | `pydantic.v1.utils.lenient_issubclass` | | `pydantic.utils.lenient_isinstance` | `pydantic.v1.utils.lenient_isinstance` | | `pydantic.utils.is_valid_field` | `pydantic.v1.utils.is_valid_field` | | `pydantic.utils.update_not_none` | `pydantic.v1.utils.update_not_none` | | `pydantic.utils.import_string` | `pydantic.v1.utils.import_string` | | `pydantic.utils.Representation` | `pydantic.v1.utils.Representation` | | `pydantic.utils.ROOT_KEY` | `pydantic.v1.utils.ROOT_KEY` | | `pydantic.utils.smart_deepcopy` | `pydantic.v1.utils.smart_deepcopy` | | `pydantic.utils.sequence_like` | `pydantic.v1.utils.sequence_like` | Removed in Pydantic V2[¶](#removed-in-pydantic-v2 "Permanent link") -------------------------------------------------------------------- * `pydantic.ConstrainedBytes` * `pydantic.ConstrainedDate` * `pydantic.ConstrainedDecimal` * `pydantic.ConstrainedFloat` * `pydantic.ConstrainedFrozenSet` * `pydantic.ConstrainedInt` * `pydantic.ConstrainedList` * `pydantic.ConstrainedSet` * `pydantic.ConstrainedStr` * `pydantic.JsonWrapper` * `pydantic.NoneBytes` * This was an alias to `None | bytes`. * `pydantic.NoneStr` * This was an alias to `None | str`. * `pydantic.NoneStrBytes` * This was an alias to `None | str | bytes`. * `pydantic.Protocol` * `pydantic.Required` * `pydantic.StrBytes` * This was an alias to `str | bytes`. * `pydantic.compiled` * `pydantic.config.get_config` * `pydantic.config.inherit_config` * `pydantic.config.prepare_config` * `pydantic.create_model_from_namedtuple` * `pydantic.create_model_from_typeddict` * `pydantic.dataclasses.create_pydantic_model_from_dataclass` * `pydantic.dataclasses.make_dataclass_validator` * `pydantic.dataclasses.set_validation` * `pydantic.datetime_parse.parse_date` * `pydantic.datetime_parse.parse_time` * `pydantic.datetime_parse.parse_datetime` * `pydantic.datetime_parse.parse_duration` * `pydantic.error_wrappers.ErrorWrapper` * `pydantic.errors.AnyStrMaxLengthError` * `pydantic.errors.AnyStrMinLengthError` * `pydantic.errors.ArbitraryTypeError` * `pydantic.errors.BoolError` * `pydantic.errors.BytesError` * `pydantic.errors.CallableError` * `pydantic.errors.ClassError` * `pydantic.errors.ColorError` * `pydantic.errors.ConfigError` * `pydantic.errors.DataclassTypeError` * `pydantic.errors.DateError` * `pydantic.errors.DateNotInTheFutureError` * `pydantic.errors.DateNotInThePastError` * `pydantic.errors.DateTimeError` * `pydantic.errors.DecimalError` * `pydantic.errors.DecimalIsNotFiniteError` * `pydantic.errors.DecimalMaxDigitsError` * `pydantic.errors.DecimalMaxPlacesError` * `pydantic.errors.DecimalWholeDigitsError` * `pydantic.errors.DictError` * `pydantic.errors.DurationError` * `pydantic.errors.EmailError` * `pydantic.errors.EnumError` * `pydantic.errors.EnumMemberError` * `pydantic.errors.ExtraError` * `pydantic.errors.FloatError` * `pydantic.errors.FrozenSetError` * `pydantic.errors.FrozenSetMaxLengthError` * `pydantic.errors.FrozenSetMinLengthError` * `pydantic.errors.HashableError` * `pydantic.errors.IPv4AddressError` * `pydantic.errors.IPv4InterfaceError` * `pydantic.errors.IPv4NetworkError` * `pydantic.errors.IPv6AddressError` * `pydantic.errors.IPv6InterfaceError` * `pydantic.errors.IPv6NetworkError` * `pydantic.errors.IPvAnyAddressError` * `pydantic.errors.IPvAnyInterfaceError` * `pydantic.errors.IPvAnyNetworkError` * `pydantic.errors.IntEnumError` * `pydantic.errors.IntegerError` * `pydantic.errors.InvalidByteSize` * `pydantic.errors.InvalidByteSizeUnit` * `pydantic.errors.InvalidDiscriminator` * `pydantic.errors.InvalidLengthForBrand` * `pydantic.errors.JsonError` * `pydantic.errors.JsonTypeError` * `pydantic.errors.ListError` * `pydantic.errors.ListMaxLengthError` * `pydantic.errors.ListMinLengthError` * `pydantic.errors.ListUniqueItemsError` * `pydantic.errors.LuhnValidationError` * `pydantic.errors.MissingDiscriminator` * `pydantic.errors.MissingError` * `pydantic.errors.NoneIsAllowedError` * `pydantic.errors.NoneIsNotAllowedError` * `pydantic.errors.NotDigitError` * `pydantic.errors.NotNoneError` * `pydantic.errors.NumberNotGeError` * `pydantic.errors.NumberNotGtError` * `pydantic.errors.NumberNotLeError` * `pydantic.errors.NumberNotLtError` * `pydantic.errors.NumberNotMultipleError` * `pydantic.errors.PathError` * `pydantic.errors.PathNotADirectoryError` * `pydantic.errors.PathNotAFileError` * `pydantic.errors.PathNotExistsError` * `pydantic.errors.PatternError` * `pydantic.errors.PyObjectError` * `pydantic.errors.PydanticTypeError` * `pydantic.errors.PydanticValueError` * `pydantic.errors.SequenceError` * `pydantic.errors.SetError` * `pydantic.errors.SetMaxLengthError` * `pydantic.errors.SetMinLengthError` * `pydantic.errors.StrError` * `pydantic.errors.StrRegexError` * `pydantic.errors.StrictBoolError` * `pydantic.errors.SubclassError` * `pydantic.errors.TimeError` * `pydantic.errors.TupleError` * `pydantic.errors.TupleLengthError` * `pydantic.errors.UUIDError` * `pydantic.errors.UUIDVersionError` * `pydantic.errors.UrlError` * `pydantic.errors.UrlExtraError` * `pydantic.errors.UrlHostError` * `pydantic.errors.UrlHostTldError` * `pydantic.errors.UrlPortError` * `pydantic.errors.UrlSchemeError` * `pydantic.errors.UrlSchemePermittedError` * `pydantic.errors.UrlUserInfoError` * `pydantic.errors.WrongConstantError` * `pydantic.main.validate_model` * `pydantic.networks.stricturl` * `pydantic.parse_file_as` * `pydantic.parse_raw_as` * `pydantic.stricturl` * `pydantic.tools.parse_file_as` * `pydantic.tools.parse_raw_as` * `pydantic.types.JsonWrapper` * `pydantic.types.NoneBytes` * `pydantic.types.NoneStr` * `pydantic.types.NoneStrBytes` * `pydantic.types.PyObject` * `pydantic.types.StrBytes` * `pydantic.typing.evaluate_forwardref` * `pydantic.typing.AbstractSetIntStr` * `pydantic.typing.AnyCallable` * `pydantic.typing.AnyClassMethod` * `pydantic.typing.CallableGenerator` * `pydantic.typing.DictAny` * `pydantic.typing.DictIntStrAny` * `pydantic.typing.DictStrAny` * `pydantic.typing.IntStr` * `pydantic.typing.ListStr` * `pydantic.typing.MappingIntStrAny` * `pydantic.typing.NoArgAnyCallable` * `pydantic.typing.NoneType` * `pydantic.typing.ReprArgs` * `pydantic.typing.SetStr` * `pydantic.typing.StrPath` * `pydantic.typing.TupleGenerator` * `pydantic.typing.WithArgsTypes` * `pydantic.typing.all_literal_values` * `pydantic.typing.display_as_type` * `pydantic.typing.get_all_type_hints` * `pydantic.typing.get_args` * `pydantic.typing.get_origin` * `pydantic.typing.get_sub_types` * `pydantic.typing.is_callable_type` * `pydantic.typing.is_classvar` * `pydantic.typing.is_finalvar` * `pydantic.typing.is_literal_type` * `pydantic.typing.is_namedtuple` * `pydantic.typing.is_new_type` * `pydantic.typing.is_none_type` * `pydantic.typing.is_typeddict` * `pydantic.typing.is_typeddict_special` * `pydantic.typing.is_union` * `pydantic.typing.new_type_supertype` * `pydantic.typing.resolve_annotations` * `pydantic.typing.typing_base` * `pydantic.typing.update_field_forward_refs` * `pydantic.typing.update_model_forward_refs` * `pydantic.utils.ClassAttribute` * `pydantic.utils.DUNDER_ATTRIBUTES` * `pydantic.utils.PyObjectStr` * `pydantic.utils.ValueItems` * `pydantic.utils.almost_equal_floats` * `pydantic.utils.get_discriminator_alias_and_values` * `pydantic.utils.get_model` * `pydantic.utils.get_unique_discriminator_alias` * `pydantic.utils.in_ipython` * `pydantic.utils.is_valid_identifier` * `pydantic.utils.path_type` * `pydantic.utils.validate_field_name` * `pydantic.validate_model` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Version Policy - Pydantic Version Policy ============== First of all, we recognize that the transitions from Pydantic V1 to V2 has been and will be painful for some users. We're sorry about this pain ![🙏](https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/svg/1f64f.svg ":pray:"), it was an unfortunate but necessary step to correct design mistakes of V1. **There will not be another breaking change of this magnitude!** Pydantic V1[¶](#pydantic-v1 "Permanent link") ---------------------------------------------- Active development of V1 has already stopped, however critical bug fixes and security vulnerabilities will be fixed in V1 until the release of Pydantic V3. Pydantic V2[¶](#pydantic-v2 "Permanent link") ---------------------------------------------- We will not intentionally make breaking changes in minor releases of V2. Functionality marked as deprecated will not be removed until the next major V3 release. Of course, some apparently safe changes and bug fixes will inevitably break some users' code — obligatory link to [xkcd](https://xkcd.com/1172/) . The following changes will **NOT** be considered breaking changes, and may occur in minor releases: * Changing the format of JSON Schema [references](https://json-schema.org/understanding-json-schema/structuring#dollarref) . * Changing the `msg`, `ctx`, and `loc` fields of [`ValidationError`](../api/pydantic_core/#pydantic_core.ValidationError) exceptions. `type` will not change — if you're programmatically parsing error messages, you should use `type`. * Adding new keys to [`ValidationError`](../api/pydantic_core/#pydantic_core.ValidationError) exceptions — e.g. we intend to add `line_number` and `column_number` to errors when validating JSON once we migrate to a new JSON parser. * Adding new [`ValidationError`](../api/pydantic_core/#pydantic_core.ValidationError) errors. * Changing how `__repr__` behaves, even of public classes. In all cases we will aim to minimize churn and do so only when justified by the increase of quality of Pydantic for users. Pydantic V3 and beyond[¶](#pydantic-v3-and-beyond "Permanent link") -------------------------------------------------------------------- We expect to make new major releases roughly once a year going forward, although as mentioned above, any associated breaking changes should be trivial to fix compared to the V1-to-V2 transition. Experimental Features[¶](#experimental-features "Permanent link") ------------------------------------------------------------------ At Pydantic, we like to move quickly and innovate! To that end, we may introduce experimental features in minor releases. Usage Documentation To learn more about our current experimental features, see the [experimental features documentation](../concepts/experimental/) . Please keep in mind, experimental features are active works in progress. If these features are successful, they'll eventually become part of Pydantic. If unsuccessful, said features will be removed with little notice. While in its experimental phase, a feature's API and behaviors may not be stable, and it's very possible that changes made to the feature will not be backward-compatible. ### Naming Conventions[¶](#naming-conventions "Permanent link") We use one of the following naming conventions to indicate that a feature is experimental: 1. The feature is located in the [`experimental`](../api/experimental/) module. In this case, you can access the feature like this: `from pydantic.experimental import feature_name` 2. The feature is located in the main module, but prefixed with `experimental_`. This case occurs when we add a new field, argument, or method to an existing data structure already within the main `pydantic` module. New features with these naming conventions are subject to change or removal, and we are looking for feedback and suggestions before making them a permanent part of Pydantic. See the [feedback section](../concepts/experimental/#feedback) for more information. ### Importing Experimental Features[¶](#importing-experimental-features "Permanent link") When you import an experimental feature from the [`experimental`](../api/experimental/) module, you'll see a warning message that the feature is experimental. You can disable this warning with the following: `import warnings from pydantic import PydanticExperimentalWarning warnings.filterwarnings('ignore', category=PydanticExperimentalWarning)` ### Lifecycle of Experimental Features[¶](#lifecycle-of-experimental-features "Permanent link") 1. A new feature is added, either in the [`experimental`](../api/experimental/) module or with the `experimental_` prefix. 2. The behavior is often modified during patch/minor releases, with potential API/behavior changes. 3. If the feature is successful, we promote it to Pydantic with the following steps: a. If it was in the [`experimental`](../api/experimental/) module, the feature is cloned to Pydantic's main module. The original experimental feature still remains in the [`experimental`](../api/experimental/) module, but it will show a warning when used. If the feature was already in the main Pydantic module, we create a copy of the feature without the `experimental_` prefix, so the feature exists with both the official and experimental names. A deprecation warning is attached to the experimental version. b. At some point, the code of the experimental feature is removed, but there will still be a stub of the feature that provides an error message with appropriate instructions. c. As a last step, the experimental version of the feature is entirely removed from the codebase. If the feature is unsuccessful or unpopular, it's removed with little notice. A stub will remain in the location of the deprecated feature with an error message. Thanks to [streamlit](https://docs.streamlit.io/develop/quick-reference/prerelease) for the inspiration for the lifecycle and naming conventions of our new experimental feature patterns. Support for Python versions[¶](#support-for-python-versions "Permanent link") ------------------------------------------------------------------------------ Pydantic will drop support for a Python version when the following conditions are met: * The Python version has reached its [expected end of life](https://devguide.python.org/versions/) . * less than 5% of downloads of the most recent minor release are using that version. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Why use Pydantic - Pydantic Why use Pydantic?[¶](#why-use-pydantic "Permanent link") ========================================================= Today, Pydantic is downloaded many times a month and used by some of the largest and most recognisable organisations in the world. It's hard to know why so many people have adopted Pydantic since its inception six years ago, but here are a few guesses. Type hints powering schema validation[¶](#type-hints "Permanent link") ----------------------------------------------------------------------- The schema that Pydantic validates against is generally defined by Python [type hints](https://docs.python.org/3/glossary.html#term-type-hint) . Type hints are great for this since, if you're writing modern Python, you already know how to use them. Using type hints also means that Pydantic integrates well with static typing tools (like [mypy](https://www.mypy-lang.org/) and [Pyright](https://github.com/microsoft/pyright/) ) and IDEs (like [PyCharm](https://www.jetbrains.com/pycharm/) and [VSCode](https://code.visualstudio.com/) ). Example - just type hints `from typing import Annotated, Literal from annotated_types import Gt from pydantic import BaseModel class Fruit(BaseModel): name: str # (1)! color: Literal['red', 'green'] # (2)! weight: Annotated[float, Gt(0)] # (3)! bazam: dict[str, list[tuple[int, bool, float]]] # (4)! print( Fruit( name='Apple', color='red', weight=4.2, bazam={'foobar': [(1, True, 0.1)]}, ) ) #> name='Apple' color='red' weight=4.2 bazam={'foobar': [(1, True, 0.1)]}` 1. The `name` field is simply annotated with `str` — any string is allowed. 2. The [`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal) type is used to enforce that `color` is either `'red'` or `'green'`. 3. Even when we want to apply constraints not encapsulated in Python types, we can use [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) and [`annotated-types`](https://github.com/annotated-types/annotated-types) to enforce constraints while still keeping typing support. 4. I'm not claiming "bazam" is really an attribute of fruit, but rather to show that arbitrarily complex types can easily be validated. Learn more See the [documentation on supported types](../concepts/types/) . Performance[¶](#performance "Permanent link") ---------------------------------------------- Pydantic's core validation logic is implemented in a separate package ([`pydantic-core`](https://github.com/pydantic/pydantic-core) ), where validation for most types is implemented in Rust. As a result, Pydantic is among the fastest data validation libraries for Python. Performance Example - Pydantic vs. dedicated code In general, dedicated code should be much faster than a general-purpose validator, but in this example Pydantic is >300% faster than dedicated code when parsing JSON and validating URLs. Performance Example `import json import timeit from urllib.parse import urlparse import requests from pydantic import HttpUrl, TypeAdapter reps = 7 number = 100 r = requests.get('https://api.github.com/emojis') r.raise_for_status() emojis_json = r.content def emojis_pure_python(raw_data): data = json.loads(raw_data) output = {} for key, value in data.items(): assert isinstance(key, str) url = urlparse(value) assert url.scheme in ('https', 'http') output[key] = url emojis_pure_python_times = timeit.repeat( 'emojis_pure_python(emojis_json)', globals={ 'emojis_pure_python': emojis_pure_python, 'emojis_json': emojis_json, }, repeat=reps, number=number, ) print(f'pure python: {min(emojis_pure_python_times) / number * 1000:0.2f}ms') #> pure python: 5.32ms type_adapter = TypeAdapter(dict[str, HttpUrl]) emojis_pydantic_times = timeit.repeat( 'type_adapter.validate_json(emojis_json)', globals={ 'type_adapter': type_adapter, 'HttpUrl': HttpUrl, 'emojis_json': emojis_json, }, repeat=reps, number=number, ) print(f'pydantic: {min(emojis_pydantic_times) / number * 1000:0.2f}ms') #> pydantic: 1.54ms print( f'Pydantic {min(emojis_pure_python_times) / min(emojis_pydantic_times):0.2f}x faster' ) #> Pydantic 3.45x faster` Unlike other performance-centric libraries written in compiled languages, Pydantic also has excellent support for customizing validation via [functional validators](#customisation) . Learn more Samuel Colvin's [talk at PyCon 2023](https://youtu.be/pWZw7hYoRVU) explains how [`pydantic-core`](https://github.com/pydantic/pydantic-core) works and how it integrates with Pydantic. Serialization[¶](#serialization "Permanent link") -------------------------------------------------- Pydantic provides functionality to serialize model in three ways: 1. To a Python `dict` made up of the associated Python objects. 2. To a Python `dict` made up only of "jsonable" types. 3. To a JSON string. In all three modes, the output can be customized by excluding specific fields, excluding unset fields, excluding default values, and excluding `None` values. Example - Serialization 3 ways `from datetime import datetime from pydantic import BaseModel class Meeting(BaseModel): when: datetime where: bytes why: str = 'No idea' m = Meeting(when='2020-01-01T12:00', where='home') print(m.model_dump(exclude_unset=True)) #> {'when': datetime.datetime(2020, 1, 1, 12, 0), 'where': b'home'} print(m.model_dump(exclude={'where'}, mode='json')) #> {'when': '2020-01-01T12:00:00', 'why': 'No idea'} print(m.model_dump_json(exclude_defaults=True)) #> {"when":"2020-01-01T12:00:00","where":"home"}` Learn more See the [documentation on serialization](../concepts/serialization/) . JSON Schema[¶](#json-schema "Permanent link") ---------------------------------------------- A [JSON Schema](https://json-schema.org/) can be generated for any Pydantic schema — allowing self-documenting APIs and integration with a wide variety of tools which support the JSON Schema format. Example - JSON Schema `from datetime import datetime from pydantic import BaseModel class Address(BaseModel): street: str city: str zipcode: str class Meeting(BaseModel): when: datetime where: Address why: str = 'No idea' print(Meeting.model_json_schema()) """ { '$defs': { 'Address': { 'properties': { 'street': {'title': 'Street', 'type': 'string'}, 'city': {'title': 'City', 'type': 'string'}, 'zipcode': {'title': 'Zipcode', 'type': 'string'}, }, 'required': ['street', 'city', 'zipcode'], 'title': 'Address', 'type': 'object', } }, 'properties': { 'when': {'format': 'date-time', 'title': 'When', 'type': 'string'}, 'where': {'$ref': '#/$defs/Address'}, 'why': {'default': 'No idea', 'title': 'Why', 'type': 'string'}, }, 'required': ['when', 'where'], 'title': 'Meeting', 'type': 'object', } """` Pydantic is compliant with the latest version of JSON Schema specification ([2020-12](https://json-schema.org/draft/2020-12/release-notes.html) ), which is compatible with [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0.html) . Learn more See the [documentation on JSON Schema](../concepts/json_schema/) . Strict mode and data coercion[¶](#strict-lax "Permanent link") --------------------------------------------------------------- By default, Pydantic is tolerant to common incorrect types and coerces data to the right type — e.g. a numeric string passed to an `int` field will be parsed as an `int`. Pydantic also has as [strict mode](../concepts/strict_mode/) , where types are not coerced and a validation error is raised unless the input data exactly matches the expected schema. But strict mode would be pretty useless when validating JSON data since JSON doesn't have types matching many common Python types like [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) , [`UUID`](https://docs.python.org/3/library/uuid.html#uuid.UUID) or [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) . To solve this, Pydantic can parse and validate JSON in one step. This allows sensible data conversion (e.g. when parsing strings into [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) objects). Since the JSON parsing is implemented in Rust, it's also very performant. Example - Strict mode that's actually useful `from datetime import datetime from pydantic import BaseModel, ValidationError class Meeting(BaseModel): when: datetime where: bytes m = Meeting.model_validate({'when': '2020-01-01T12:00', 'where': 'home'}) print(m) #> when=datetime.datetime(2020, 1, 1, 12, 0) where=b'home' try: m = Meeting.model_validate( {'when': '2020-01-01T12:00', 'where': 'home'}, strict=True ) except ValidationError as e: print(e) """ 2 validation errors for Meeting when Input should be a valid datetime [type=datetime_type, input_value='2020-01-01T12:00', input_type=str] where Input should be a valid bytes [type=bytes_type, input_value='home', input_type=str] """ m_json = Meeting.model_validate_json( '{"when": "2020-01-01T12:00", "where": "home"}' ) print(m_json) #> when=datetime.datetime(2020, 1, 1, 12, 0) where=b'home'` Learn more See the [documentation on strict mode](../concepts/strict_mode/) . Dataclasses, TypedDicts, and more[¶](#dataclasses-typeddict-more "Permanent link") ----------------------------------------------------------------------------------- Pydantic provides four ways to create schemas and perform validation and serialization: 1. [`BaseModel`](../concepts/models/) — Pydantic's own super class with many common utilities available via instance methods. 2. [Pydantic dataclasses](../concepts/dataclasses/) — a wrapper around standard dataclasses with additional validation performed. 3. [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) — a general way to adapt any type for validation and serialization. This allows types like [`TypedDict`](../api/standard_library_types/#typeddict) and [`NamedTuple`](../api/standard_library_types/#typingnamedtuple) to be validated as well as simple types (like [`int`](https://docs.python.org/3/library/functions.html#int) or [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) ) — [all types](../concepts/types/) supported can be used with [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) . 4. [`validate_call`](../concepts/validation_decorator/) — a decorator to perform validation when calling a function. Example - schema based on a [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) `from datetime import datetime from typing_extensions import NotRequired, TypedDict from pydantic import TypeAdapter class Meeting(TypedDict): when: datetime where: bytes why: NotRequired[str] meeting_adapter = TypeAdapter(Meeting) m = meeting_adapter.validate_python( # (1)! {'when': '2020-01-01T12:00', 'where': 'home'} ) print(m) #> {'when': datetime.datetime(2020, 1, 1, 12, 0), 'where': b'home'} meeting_adapter.dump_python(m, exclude={'where'}) # (2)! print(meeting_adapter.json_schema()) # (3)! """ { 'properties': { 'when': {'format': 'date-time', 'title': 'When', 'type': 'string'}, 'where': {'format': 'binary', 'title': 'Where', 'type': 'string'}, 'why': {'title': 'Why', 'type': 'string'}, }, 'required': ['when', 'where'], 'title': 'Meeting', 'type': 'object', } """` 1. [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) for a [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) performing validation, it can also validate JSON data directly with [`validate_json`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter.validate_json) . 2. [`dump_python`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter.dump_python) to serialise a [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) to a python object, it can also serialise to JSON with [`dump_json`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter.dump_json) . 3. [`TypeAdapter`](../api/type_adapter/#pydantic.type_adapter.TypeAdapter) can also generate a JSON Schema. Customisation[¶](#customisation "Permanent link") -------------------------------------------------- Functional validators and serializers, as well as a powerful protocol for custom types, means the way Pydantic operates can be customized on a per-field or per-type basis. Customisation Example - wrap validators "wrap validators" are new in Pydantic V2 and are one of the most powerful ways to customize validation. `from datetime import datetime, timezone from typing import Any from pydantic_core.core_schema import ValidatorFunctionWrapHandler from pydantic import BaseModel, field_validator class Meeting(BaseModel): when: datetime @field_validator('when', mode='wrap') def when_now( cls, input_value: Any, handler: ValidatorFunctionWrapHandler ) -> datetime: if input_value == 'now': return datetime.now() when = handler(input_value) # in this specific application we know tz naive datetimes are in UTC if when.tzinfo is None: when = when.replace(tzinfo=timezone.utc) return when print(Meeting(when='2020-01-01T12:00+01:00')) #> when=datetime.datetime(2020, 1, 1, 12, 0, tzinfo=TzInfo(+01:00)) print(Meeting(when='now')) #> when=datetime.datetime(2032, 1, 2, 3, 4, 5, 6) print(Meeting(when='2020-01-01T12:00')) #> when=datetime.datetime(2020, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)` Learn more See the documentation on [validators](../concepts/validators/) , [custom serializers](../concepts/serialization/#custom-serializers) , and [custom types](../concepts/types/#custom-types) . Ecosystem[¶](#ecosystem "Permanent link") ------------------------------------------ At the time of writing there are 466,400 repositories on GitHub and 8,119 packages on PyPI that depend on Pydantic. Some notable libraries that depend on Pydantic: * [`huggingface/transformers`](https://github.com/huggingface/transformers) 138,570 stars * [`hwchase17/langchain`](https://github.com/hwchase17/langchain) 99,542 stars * [`tiangolo/fastapi`](https://github.com/tiangolo/fastapi) 80,497 stars * [`apache/airflow`](https://github.com/apache/airflow) 38,577 stars * [`lm-sys/FastChat`](https://github.com/lm-sys/FastChat) 37,650 stars * [`microsoft/DeepSpeed`](https://github.com/microsoft/DeepSpeed) 36,521 stars * [`OpenBB-finance/OpenBBTerminal`](https://github.com/OpenBB-finance/OpenBBTerminal) 35,971 stars * [`gradio-app/gradio`](https://github.com/gradio-app/gradio) 35,740 stars * [`ray-project/ray`](https://github.com/ray-project/ray) 35,176 stars * [`pola-rs/polars`](https://github.com/pola-rs/polars) 31,698 stars * [`Lightning-AI/lightning`](https://github.com/Lightning-AI/lightning) 28,902 stars * [`mindsdb/mindsdb`](https://github.com/mindsdb/mindsdb) 27,141 stars * [`embedchain/embedchain`](https://github.com/embedchain/embedchain) 24,379 stars * [`pynecone-io/reflex`](https://github.com/pynecone-io/reflex) 21,558 stars * [`heartexlabs/label-studio`](https://github.com/heartexlabs/label-studio) 20,571 stars * [`Sanster/lama-cleaner`](https://github.com/Sanster/lama-cleaner) 20,313 stars * [`mlflow/mlflow`](https://github.com/mlflow/mlflow) 19,393 stars * [`RasaHQ/rasa`](https://github.com/RasaHQ/rasa) 19,337 stars * [`spotDL/spotify-downloader`](https://github.com/spotDL/spotify-downloader) 18,604 stars * [`chroma-core/chroma`](https://github.com/chroma-core/chroma) 17,393 stars * [`airbytehq/airbyte`](https://github.com/airbytehq/airbyte) 17,120 stars * [`openai/evals`](https://github.com/openai/evals) 15,437 stars * [`tiangolo/sqlmodel`](https://github.com/tiangolo/sqlmodel) 15,127 stars * [`ydataai/ydata-profiling`](https://github.com/ydataai/ydata-profiling) 12,687 stars * [`pyodide/pyodide`](https://github.com/pyodide/pyodide) 12,653 stars * [`dagster-io/dagster`](https://github.com/dagster-io/dagster) 12,440 stars * [`PaddlePaddle/PaddleNLP`](https://github.com/PaddlePaddle/PaddleNLP) 12,312 stars * [`matrix-org/synapse`](https://github.com/matrix-org/synapse) 11,857 stars * [`lucidrains/DALLE2-pytorch`](https://github.com/lucidrains/DALLE2-pytorch) 11,207 stars * [`great-expectations/great_expectations`](https://github.com/great-expectations/great_expectations) 10,164 stars * [`modin-project/modin`](https://github.com/modin-project/modin) 10,002 stars * [`aws/serverless-application-model`](https://github.com/aws/serverless-application-model) 9,402 stars * [`sqlfluff/sqlfluff`](https://github.com/sqlfluff/sqlfluff) 8,535 stars * [`replicate/cog`](https://github.com/replicate/cog) 8,344 stars * [`autogluon/autogluon`](https://github.com/autogluon/autogluon) 8,326 stars * [`lucidrains/imagen-pytorch`](https://github.com/lucidrains/imagen-pytorch) 8,164 stars * [`brycedrennan/imaginAIry`](https://github.com/brycedrennan/imaginAIry) 8,050 stars * [`vitalik/django-ninja`](https://github.com/vitalik/django-ninja) 7,685 stars * [`NVlabs/SPADE`](https://github.com/NVlabs/SPADE) 7,632 stars * [`bridgecrewio/checkov`](https://github.com/bridgecrewio/checkov) 7,340 stars * [`bentoml/BentoML`](https://github.com/bentoml/BentoML) 7,322 stars * [`skypilot-org/skypilot`](https://github.com/skypilot-org/skypilot) 7,113 stars * [`apache/iceberg`](https://github.com/apache/iceberg) 6,853 stars * [`deeppavlov/DeepPavlov`](https://github.com/deeppavlov/DeepPavlov) 6,777 stars * [`PrefectHQ/marvin`](https://github.com/PrefectHQ/marvin) 5,454 stars * [`NVIDIA/NeMo-Guardrails`](https://github.com/NVIDIA/NeMo-Guardrails) 4,383 stars * [`microsoft/FLAML`](https://github.com/microsoft/FLAML) 4,035 stars * [`jina-ai/discoart`](https://github.com/jina-ai/discoart) 3,846 stars * [`docarray/docarray`](https://github.com/docarray/docarray) 3,007 stars * [`aws-powertools/powertools-lambda-python`](https://github.com/aws-powertools/powertools-lambda-python) 2,980 stars * [`roman-right/beanie`](https://github.com/roman-right/beanie) 2,172 stars * [`art049/odmantic`](https://github.com/art049/odmantic) 1,096 stars More libraries using Pydantic can be found at [`Kludex/awesome-pydantic`](https://github.com/Kludex/awesome-pydantic) . Organisations using Pydantic[¶](#using-pydantic "Permanent link") ------------------------------------------------------------------ Some notable companies and organisations using Pydantic together with comments on why/how we know they're using Pydantic. The organisations below are included because they match one or more of the following criteria: * Using Pydantic as a dependency in a public repository. * Referring traffic to the Pydantic documentation site from an organization-internal domain — specific referrers are not included since they're generally not in the public domain. * Direct communication between the Pydantic team and engineers employed by the organization about usage of Pydantic within the organization. We've included some extra detail where appropriate and already in the public domain. ### Adobe[¶](#org-adobe "Permanent link") [`adobe/dy-sql`](https://github.com/adobe/dy-sql) uses Pydantic. ### Amazon and AWS[¶](#org-amazon "Permanent link") * [powertools-lambda-python](https://github.com/aws-powertools/powertools-lambda-python) * [awslabs/gluonts](https://github.com/awslabs/gluonts) * AWS [sponsored Samuel Colvin $5,000](https://twitter.com/samuel_colvin/status/1549383169006239745) to work on Pydantic in 2022 ### Anthropic[¶](#org-anthropic "Permanent link") [`anthropics/anthropic-sdk-python`](https://github.com/anthropics/anthropic-sdk-python) uses Pydantic. ### Apple[¶](#org-apple "Permanent link") _(Based on the criteria described above)_ ### ASML[¶](#org-asml "Permanent link") _(Based on the criteria described above)_ ### AstraZeneca[¶](#org-astrazeneca "Permanent link") [Multiple repos](https://github.com/search?q=org%3AAstraZeneca+pydantic&type=code) in the `AstraZeneca` GitHub org depend on Pydantic. ### Cisco Systems[¶](#org-cisco "Permanent link") * Pydantic is listed in their report of [Open Source Used In RADKit](https://www.cisco.com/c/dam/en_us/about/doing_business/open_source/docs/RADKit-149-1687424532.pdf) . * [`cisco/webex-assistant-sdk`](https://github.com/cisco/webex-assistant-sdk) ### Comcast[¶](#org-comcast "Permanent link") _(Based on the criteria described above)_ ### Datadog[¶](#org-datadog "Permanent link") * Extensive use of Pydantic in [`DataDog/integrations-core`](https://github.com/DataDog/integrations-core) and other repos * Communication with engineers from Datadog about how they use Pydantic. ### Facebook[¶](#org-facebook "Permanent link") [Multiple repos](https://github.com/search?q=org%3Afacebookresearch+pydantic&type=code) in the `facebookresearch` GitHub org depend on Pydantic. ### GitHub[¶](#org-github "Permanent link") GitHub sponsored Pydantic $750 in 2022 ### Google[¶](#org-google "Permanent link") Extensive use of Pydantic in [`google/turbinia`](https://github.com/google/turbinia) and other repos. ### HSBC[¶](#org-hsbc "Permanent link") _(Based on the criteria described above)_ ### IBM[¶](#org-ibm "Permanent link") [Multiple repos](https://github.com/search?q=org%3AIBM+pydantic&type=code) in the `IBM` GitHub org depend on Pydantic. ### Intel[¶](#org-intel "Permanent link") _(Based on the criteria described above)_ ### Intuit[¶](#org-intuit "Permanent link") _(Based on the criteria described above)_ ### Intergovernmental Panel on Climate Change[¶](#org-ipcc "Permanent link") [Tweet](https://twitter.com/daniel_huppmann/status/1563461797973110785) explaining how the IPCC use Pydantic. ### JPMorgan[¶](#org-jpmorgan "Permanent link") _(Based on the criteria described above)_ ### Jupyter[¶](#org-jupyter "Permanent link") * The developers of the Jupyter notebook are using Pydantic [for subprojects](https://github.com/pydantic/pydantic/issues/773) * Through the FastAPI-based Jupyter server [Jupyverse](https://github.com/jupyter-server/jupyverse) * [FPS](https://github.com/jupyter-server/fps) 's configuration management. ### Microsoft[¶](#org-microsoft "Permanent link") * [DeepSpeed](https://github.com/microsoft/DeepSpeed) deep learning optimisation library uses Pydantic extensively * [Multiple repos](https://github.com/search?q=org%3Amicrosoft%20pydantic&type=code) in the `microsoft` GitHub org depend on Pydantic, in particular their * Pydantic is also [used](https://github.com/search?q=org%3AAzure%20pydantic&type=code) in the `Azure` GitHub org * [Comments](https://github.com/tiangolo/fastapi/pull/26) on GitHub show Microsoft engineers using Pydantic as part of Windows and Office ### Molecular Science Software Institute[¶](#org-molssi "Permanent link") [Multiple repos](https://github.com/search?q=org%3AMolSSI%20pydantic&type=code) in the `MolSSI` GitHub org depend on Pydantic. ### NASA[¶](#org-nasa "Permanent link") [Multiple repos](https://github.com/search?q=org%3Anasa%20pydantic&type=code) in the `NASA` GitHub org depend on Pydantic. NASA are also using Pydantic via FastAPI in their JWST project to process images from the James Webb Space Telescope, see [this tweet](https://twitter.com/benjamin_falk/status/1546947039363305472) . ### Netflix[¶](#org-netflix "Permanent link") [Multiple repos](https://github.com/search?q=org%3Anetflix%20pydantic&type=code) in the `Netflix` GitHub org depend on Pydantic. ### NSA[¶](#org-nsa "Permanent link") The [`nsacyber/WALKOFF`](https://github.com/nsacyber/WALKOFF) repo depends on Pydantic. ### NVIDIA[¶](#org-nvidia "Permanent link") [Multiple repositories](https://github.com/search?q=org%3ANVIDIA%20pydantic&type=code) in the `NVIDIA` GitHub org depend on Pydantic. Their "Omniverse Services" depends on Pydantic according to [their documentation](https://web.archive.org/web/20220628161919/https://docs.omniverse.nvidia.com/prod_services/prod_services/core/index.html) . ### OpenAI[¶](#org-openai "Permanent link") OpenAI use Pydantic for their ChatCompletions API, as per [this](https://github.com/pydantic/pydantic/discussions/6372) discussion on GitHub. Anecdotally, OpenAI use Pydantic extensively for their internal services. ### Oracle[¶](#org-oracle "Permanent link") _(Based on the criteria described above)_ ### Palantir[¶](#org-palantir "Permanent link") _(Based on the criteria described above)_ ### Qualcomm[¶](#org-qualcomm "Permanent link") _(Based on the criteria described above)_ ### Red Hat[¶](#org-redhat "Permanent link") _(Based on the criteria described above)_ ### Revolut[¶](#org-revolut "Permanent link") Anecdotally, all internal services at Revolut are built with FastAPI and therefore Pydantic. ### Robusta[¶](#org-robusta "Permanent link") The [`robusta-dev/robusta`](https://github.com/robusta-dev/robusta) repo depends on Pydantic. ### Salesforce[¶](#org-salesforce "Permanent link") Salesforce [sponsored Samuel Colvin $10,000](https://twitter.com/samuel_colvin/status/1501288247670063104) to work on Pydantic in 2022. ### Starbucks[¶](#org-starbucks "Permanent link") _(Based on the criteria described above)_ ### Texas Instruments[¶](#org-ti "Permanent link") _(Based on the criteria described above)_ ### Twilio[¶](#org-twilio "Permanent link") _(Based on the criteria described above)_ ### Twitter[¶](#org-twitter "Permanent link") Twitter's [`the-algorithm`](https://github.com/twitter/the-algorithm) repo where they [open sourced](https://blog.twitter.com/engineering/en_us/topics/open-source/2023/twitter-recommendation-algorithm) their recommendation engine uses Pydantic. ### UK Home Office[¶](#org-ukhomeoffice "Permanent link") _(Based on the criteria described above)_ Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Configuration - Pydantic Configuration ============= Configuration for Pydantic models. ConfigDict [¶](#pydantic.config.ConfigDict "Permanent link") ------------------------------------------------------------- Bases: `TypedDict` A TypedDict for configuring Pydantic behaviour. ### title `instance-attribute` [¶](#pydantic.config.ConfigDict.title "Permanent link") `title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The title for the generated JSON schema, defaults to the model's name ### model\_title\_generator `instance-attribute` [¶](#pydantic.config.ConfigDict.model_title_generator "Permanent link") `model_title_generator: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[type](https://docs.python.org/3/glossary.html#term-type) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None` A callable that takes a model class and returns the title for it. Defaults to `None`. ### field\_title\_generator `instance-attribute` [¶](#pydantic.config.ConfigDict.field_title_generator "Permanent link") `field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](../fields/#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") | [ComputedFieldInfo](../fields/#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None )` A callable that takes a field's name and info and returns title for it. Defaults to `None`. ### str\_to\_lower `instance-attribute` [¶](#pydantic.config.ConfigDict.str_to_lower "Permanent link") `str_to_lower: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to convert all characters to lowercase for str types. Defaults to `False`. ### str\_to\_upper `instance-attribute` [¶](#pydantic.config.ConfigDict.str_to_upper "Permanent link") `str_to_upper: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to convert all characters to uppercase for str types. Defaults to `False`. ### str\_strip\_whitespace `instance-attribute` [¶](#pydantic.config.ConfigDict.str_strip_whitespace "Permanent link") `str_strip_whitespace: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to strip leading and trailing whitespace for str types. ### str\_min\_length `instance-attribute` [¶](#pydantic.config.ConfigDict.str_min_length "Permanent link") `str_min_length: [int](https://docs.python.org/3/library/functions.html#int)` The minimum length for str types. Defaults to `None`. ### str\_max\_length `instance-attribute` [¶](#pydantic.config.ConfigDict.str_max_length "Permanent link") `str_max_length: [int](https://docs.python.org/3/library/functions.html#int) | None` The maximum length for str types. Defaults to `None`. ### extra `instance-attribute` [¶](#pydantic.config.ConfigDict.extra "Permanent link") `extra: [ExtraValues](#pydantic.config.ExtraValues "pydantic.config.ExtraValues") | None` Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`. Three configuration values are available: * `'ignore'`: Providing extra data is ignored (the default): `from pydantic import BaseModel, ConfigDict class User(BaseModel): model_config = ConfigDict(extra='ignore') # (1)! name: str user = User(name='John Doe', age=20) # (2)! print(user) #> name='John Doe'` 1. This is the default behaviour. 2. The `age` argument is ignored. * `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`](../pydantic_core/#pydantic_core.ValidationError) will be raised if this is the case: `from pydantic import BaseModel, ConfigDict, ValidationError class Model(BaseModel): x: int model_config = ConfigDict(extra='forbid') try: Model(x=1, y='a') except ValidationError as exc: print(exc) """ 1 validation error for Model y Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str] """` * `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute: `from pydantic import BaseModel, ConfigDict class Model(BaseModel): x: int model_config = ConfigDict(extra='allow') m = Model(x=1, y='a') assert m.__pydantic_extra__ == {'y': 'a'}` By default, no validation will be applied to these extra items, but you can set a type for the values by overriding the type annotation for `__pydantic_extra__`: `from pydantic import BaseModel, ConfigDict, Field, ValidationError class Model(BaseModel): __pydantic_extra__: dict[str, int] = Field(init=False) # (1)! x: int model_config = ConfigDict(extra='allow') try: Model(x=1, y='a') except ValidationError as exc: print(exc) """ 1 validation error for Model y Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str] """ m = Model(x=1, y='2') assert m.x == 1 assert m.y == 2 assert m.model_dump() == {'x': 1, 'y': 2} assert m.__pydantic_extra__ == {'y': 2}` 1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from being included as a parameter to the model's `__init__` method by type checkers. ### frozen `instance-attribute` [¶](#pydantic.config.ConfigDict.frozen "Permanent link") `frozen: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to `False`. Note On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default. ### populate\_by\_name `instance-attribute` [¶](#pydantic.config.ConfigDict.populate_by_name "Permanent link") `populate_by_name: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether an aliased field may be populated by its name as given by the model attribute, as well as the alias. Defaults to `False`. Warning `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3. Instead, you should use the [`validate_by_name`](#pydantic.config.ConfigDict.validate_by_name) configuration setting. When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the previous behavior of `populate_by_name=True`. In v2.11, we also introduced a [`validate_by_alias`](#pydantic.config.ConfigDict.validate_by_alias) setting that introduces more fine grained control for validation behavior. Here's how you might go about using the new settings to achieve the same behavior: `from pydantic import BaseModel, ConfigDict, Field class Model(BaseModel): model_config = ConfigDict(validate_by_name=True, validate_by_alias=True) my_field: str = Field(alias='my_alias') # (1)! m = Model(my_alias='foo') # (2)! print(m) #> my_field='foo' m = Model(my_alias='foo') # (3)! print(m) #> my_field='foo'` 1. The field `'my_field'` has an alias `'my_alias'`. 2. The model is populated by the alias `'my_alias'`. 3. The model is populated by the attribute name `'my_field'`. ### use\_enum\_values `instance-attribute` [¶](#pydantic.config.ConfigDict.use_enum_values "Permanent link") `use_enum_values: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to populate models with the `value` property of enums, rather than the raw enum. This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`. Note If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True` for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an enum's value occurs during validation, not serialization. `from enum import Enum from typing import Optional from pydantic import BaseModel, ConfigDict, Field class SomeEnum(Enum): FOO = 'foo' BAR = 'bar' BAZ = 'baz' class SomeModel(BaseModel): model_config = ConfigDict(use_enum_values=True) some_enum: SomeEnum another_enum: Optional[SomeEnum] = Field( default=SomeEnum.FOO, validate_default=True ) model1 = SomeModel(some_enum=SomeEnum.BAR) print(model1.model_dump()) #> {'some_enum': 'bar', 'another_enum': 'foo'} model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ) print(model2.model_dump()) #> {'some_enum': 'bar', 'another_enum': 'baz'}` ### validate\_assignment `instance-attribute` [¶](#pydantic.config.ConfigDict.validate_assignment "Permanent link") `validate_assignment: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to validate the data when the model is changed. Defaults to `False`. The default behavior of Pydantic is to validate the data when the model is created. In case the user changes the data after the model is created, the model is _not_ revalidated. `from pydantic import BaseModel class User(BaseModel): name: str user = User(name='John Doe') # (1)! print(user) #> name='John Doe' user.name = 123 # (1)! print(user) #> name=123` 1. The validation happens only when the model is created. 2. The validation does not happen when the data is changed. In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`: `from pydantic import BaseModel, ValidationError class User(BaseModel, validate_assignment=True): # (1)! name: str user = User(name='John Doe') # (2)! print(user) #> name='John Doe' try: user.name = 123 # (3)! except ValidationError as e: print(e) ''' 1 validation error for User name Input should be a valid string [type=string_type, input_value=123, input_type=int] '''` 1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`. 2. The validation happens when the model is created. 3. The validation _also_ happens when the data is changed. ### arbitrary\_types\_allowed `instance-attribute` [¶](#pydantic.config.ConfigDict.arbitrary_types_allowed "Permanent link") `arbitrary_types_allowed: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether arbitrary types are allowed for field types. Defaults to `False`. `from pydantic import BaseModel, ConfigDict, ValidationError # This is not a pydantic model, it's an arbitrary class class Pet: def __init__(self, name: str): self.name = name class Model(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) pet: Pet owner: str pet = Pet(name='Hedwig') # A simple check of instance type is used to validate the data model = Model(owner='Harry', pet=pet) print(model) #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry' print(model.pet) #> <__main__.Pet object at 0x0123456789ab> print(model.pet.name) #> Hedwig print(type(model.pet)) #> try: # If the value is not an instance of the type, it's invalid Model(owner='Harry', pet='Hedwig') except ValidationError as e: print(e) ''' 1 validation error for Model pet Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str] ''' # Nothing in the instance of the arbitrary type is checked # Here name probably should have been a str, but it's not validated pet2 = Pet(name=42) model2 = Model(owner='Harry', pet=pet2) print(model2) #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry' print(model2.pet) #> <__main__.Pet object at 0x0123456789ab> print(model2.pet.name) #> 42 print(type(model2.pet)) #> ` ### from\_attributes `instance-attribute` [¶](#pydantic.config.ConfigDict.from_attributes "Permanent link") `from_attributes: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to build models and look up discriminators of tagged unions using python object attributes. ### loc\_by\_alias `instance-attribute` [¶](#pydantic.config.ConfigDict.loc_by_alias "Permanent link") `loc_by_alias: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to use the actual key provided in the data (e.g. alias) for error `loc`s rather than the field's name. Defaults to `True`. ### alias\_generator `instance-attribute` [¶](#pydantic.config.ConfigDict.alias_generator "Permanent link") `alias_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | [AliasGenerator](../aliases/#pydantic.aliases.AliasGenerator "pydantic.aliases.AliasGenerator") | None )` A callable that takes a field name and returns an alias for it or an instance of [`AliasGenerator`](../aliases/#pydantic.aliases.AliasGenerator) . Defaults to `None`. When using a callable, the alias generator is used for both validation and serialization. If you want to use different alias generators for validation and serialization, you can use [`AliasGenerator`](../aliases/#pydantic.aliases.AliasGenerator) instead. If data source field names do not match your code style (e. g. CamelCase fields), you can automatically generate aliases using `alias_generator`. Here's an example with a basic callable: `from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_pascal class Voice(BaseModel): model_config = ConfigDict(alias_generator=to_pascal) name: str language_code: str voice = Voice(Name='Filiz', LanguageCode='tr-TR') print(voice.language_code) #> tr-TR print(voice.model_dump(by_alias=True)) #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}` If you want to use different alias generators for validation and serialization, you can use [`AliasGenerator`](../aliases/#pydantic.aliases.AliasGenerator) . `from pydantic import AliasGenerator, BaseModel, ConfigDict from pydantic.alias_generators import to_camel, to_pascal class Athlete(BaseModel): first_name: str last_name: str sport: str model_config = ConfigDict( alias_generator=AliasGenerator( validation_alias=to_camel, serialization_alias=to_pascal, ) ) athlete = Athlete(firstName='John', lastName='Doe', sport='track') print(athlete.model_dump(by_alias=True)) #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}` Note Pydantic offers three built-in alias generators: [`to_pascal`](#pydantic.alias_generators.to_pascal) , [`to_camel`](#pydantic.alias_generators.to_camel) , and [`to_snake`](#pydantic.alias_generators.to_snake) . ### ignored\_types `instance-attribute` [¶](#pydantic.config.ConfigDict.ignored_types "Permanent link") `ignored_types: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) , ...]` A tuple of types that may occur as values of class attributes without annotations. This is typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a class without an annotation and has a type that is not in this tuple (or otherwise recognized by _pydantic_), an error will be raised. Defaults to `()`. ### allow\_inf\_nan `instance-attribute` [¶](#pydantic.config.ConfigDict.allow_inf_nan "Permanent link") `allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`. ### json\_schema\_extra `instance-attribute` [¶](#pydantic.config.ConfigDict.json_schema_extra "Permanent link") `json_schema_extra: JsonDict | JsonSchemaExtraCallable | None` A dict or callable to provide extra JSON schema properties. Defaults to `None`. ### json\_encoders `instance-attribute` [¶](#pydantic.config.ConfigDict.json_encoders "Permanent link") `json_encoders: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ], JsonEncoder] | None` A `dict` of custom JSON encoders for specific types. Defaults to `None`. Deprecated This config option is a carryover from v1. We originally planned to remove it in v2 but didn't have a 1:1 replacement so we are keeping it for now. It is still deprecated and will likely be removed in the future. ### strict `instance-attribute` [¶](#pydantic.config.ConfigDict.strict "Permanent link") `strict: [bool](https://docs.python.org/3/library/functions.html#bool)` _(new in V2)_ If `True`, strict validation is applied to all fields on the model. By default, Pydantic attempts to coerce values to the correct type, when possible. There are situations in which you may want to disable this behavior, and instead raise an error if a value's type does not match the field's type annotation. To configure strict mode for all fields on a model, you can set `strict=True` on the model. `from pydantic import BaseModel, ConfigDict class Model(BaseModel): model_config = ConfigDict(strict=True) name: str age: int` See [Strict Mode](../../concepts/strict_mode/) for more details. See the [Conversion Table](../../concepts/conversion_table/) for more details on how Pydantic converts data in both strict and lax modes. ### revalidate\_instances `instance-attribute` [¶](#pydantic.config.ConfigDict.revalidate_instances "Permanent link") `revalidate_instances: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [ "always", "never", "subclass-instances" ]` When and how to revalidate models and dataclasses during validation. Accepts the string values of `'never'`, `'always'` and `'subclass-instances'`. Defaults to `'never'`. * `'never'` will not revalidate models and dataclasses during validation * `'always'` will revalidate models and dataclasses during validation * `'subclass-instances'` will revalidate models and dataclasses during validation if the instance is a subclass of the model or dataclass By default, model and dataclass instances are not revalidated during validation. `from pydantic import BaseModel class User(BaseModel, revalidate_instances='never'): # (1)! hobbies: list[str] class SubUser(User): sins: list[str] class Transaction(BaseModel): user: User my_user = User(hobbies=['reading']) t = Transaction(user=my_user) print(t) #> user=User(hobbies=['reading']) my_user.hobbies = [1] # (2)! t = Transaction(user=my_user) # (3)! print(t) #> user=User(hobbies=[1]) my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) t = Transaction(user=my_sub_user) print(t) #> user=SubUser(hobbies=['scuba diving'], sins=['lying'])` 1. `revalidate_instances` is set to `'never'` by \*\*default. 2. The assignment is not validated, unless you set `validate_assignment` to `True` in the model's config. 3. Since `revalidate_instances` is set to `never`, this is not revalidated. If you want to revalidate instances during validation, you can set `revalidate_instances` to `'always'` in the model's config. `from pydantic import BaseModel, ValidationError class User(BaseModel, revalidate_instances='always'): # (1)! hobbies: list[str] class SubUser(User): sins: list[str] class Transaction(BaseModel): user: User my_user = User(hobbies=['reading']) t = Transaction(user=my_user) print(t) #> user=User(hobbies=['reading']) my_user.hobbies = [1] try: t = Transaction(user=my_user) # (2)! except ValidationError as e: print(e) ''' 1 validation error for Transaction user.hobbies.0 Input should be a valid string [type=string_type, input_value=1, input_type=int] ''' my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) t = Transaction(user=my_sub_user) print(t) # (3)! #> user=User(hobbies=['scuba diving'])` 1. `revalidate_instances` is set to `'always'`. 2. The model is revalidated, since `revalidate_instances` is set to `'always'`. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`. It's also possible to set `revalidate_instances` to `'subclass-instances'` to only revalidate instances of subclasses of the model. `from pydantic import BaseModel class User(BaseModel, revalidate_instances='subclass-instances'): # (1)! hobbies: list[str] class SubUser(User): sins: list[str] class Transaction(BaseModel): user: User my_user = User(hobbies=['reading']) t = Transaction(user=my_user) print(t) #> user=User(hobbies=['reading']) my_user.hobbies = [1] t = Transaction(user=my_user) # (2)! print(t) #> user=User(hobbies=[1]) my_sub_user = SubUser(hobbies=['scuba diving'], sins=['lying']) t = Transaction(user=my_sub_user) print(t) # (3)! #> user=User(hobbies=['scuba diving'])` 1. `revalidate_instances` is set to `'subclass-instances'`. 2. This is not revalidated, since `my_user` is not a subclass of `User`. 3. Using `'never'` we would have gotten `user=SubUser(hobbies=['scuba diving'], sins=['lying'])`. ### ser\_json\_timedelta `instance-attribute` [¶](#pydantic.config.ConfigDict.ser_json_timedelta "Permanent link") `ser_json_timedelta: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['iso8601', 'float']` The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and `'float'`. Defaults to `'iso8601'`. * `'iso8601'` will serialize timedeltas to ISO 8601 durations. * `'float'` will serialize timedeltas to the total number of seconds. ### ser\_json\_bytes `instance-attribute` [¶](#pydantic.config.ConfigDict.ser_json_bytes "Permanent link") `ser_json_bytes: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['utf8', 'base64', 'hex']` The encoding of JSON serialized bytes. Defaults to `'utf8'`. Set equal to `val_json_bytes` to get back an equal value after serialization round trip. * `'utf8'` will serialize bytes to UTF-8 strings. * `'base64'` will serialize bytes to URL safe base64 strings. * `'hex'` will serialize bytes to hexadecimal strings. ### val\_json\_bytes `instance-attribute` [¶](#pydantic.config.ConfigDict.val_json_bytes "Permanent link") `val_json_bytes: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['utf8', 'base64', 'hex']` The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`. Set equal to `ser_json_bytes` to get back an equal value after serialization round trip. * `'utf8'` will deserialize UTF-8 strings to bytes. * `'base64'` will deserialize URL safe base64 strings to bytes. * `'hex'` will deserialize hexadecimal strings to bytes. ### ser\_json\_inf\_nan `instance-attribute` [¶](#pydantic.config.ConfigDict.ser_json_inf_nan "Permanent link") `ser_json_inf_nan: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['null', 'constants', 'strings']` The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`. * `'null'` will serialize infinity and NaN values as `null`. * `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`. * `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`. ### validate\_default `instance-attribute` [¶](#pydantic.config.ConfigDict.validate_default "Permanent link") `validate_default: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to validate default values during validation. Defaults to `False`. ### validate\_return `instance-attribute` [¶](#pydantic.config.ConfigDict.validate_return "Permanent link") `validate_return: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to validate the return value from call validators. Defaults to `False`. ### protected\_namespaces `instance-attribute` [¶](#pydantic.config.ConfigDict.protected_namespaces "Permanent link") `protected_namespaces: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/re.html#re.Pattern "re.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ], ...]` A `tuple` of strings and/or patterns that prevent models from having fields with names that conflict with them. For strings, we match on a prefix basis. Ex, if 'dog' is in the protected namespace, 'dog\_name' will be protected. For patterns, we match on the entire field name. Ex, if `re.compile(r'^dog$')` is in the protected namespace, 'dog' will be protected, but 'dog\_name' will not be. Defaults to `('model_validate', 'model_dump',)`. The reason we've selected these is to prevent collisions with other validation / dumping formats in the future - ex, `model_validate_{some_newly_supported_format}`. Before v2.10, Pydantic used `('model_',)` as the default value for this setting to prevent collisions between model attributes and `BaseModel`'s own methods. This was changed in v2.10 given feedback that this restriction was limiting in AI and data science contexts, where it is common to have fields with names like `model_id`, `model_input`, `model_output`, etc. For more details, see https://github.com/pydantic/pydantic/issues/10315. ``import warnings from pydantic import BaseModel warnings.filterwarnings('error') # Raise warnings as errors try: class Model(BaseModel): model_dump_something: str except UserWarning as e: print(e) ''' Field "model_dump_something" in Model has conflict with protected namespace "model_dump". You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('model_validate',)`. '''`` You can customize this behavior using the `protected_namespaces` setting: ``import re import warnings from pydantic import BaseModel, ConfigDict with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter('always') # Catch all warnings class Model(BaseModel): safe_field: str also_protect_field: str protect_this: str model_config = ConfigDict( protected_namespaces=( 'protect_me_', 'also_protect_', re.compile('^protect_this$'), ) ) for warning in caught_warnings: print(f'{warning.message}') ''' Field "also_protect_field" in Model has conflict with protected namespace "also_protect_". You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', re.compile('^protect_this$'))`. Field "protect_this" in Model has conflict with protected namespace "re.compile('^protect_this$')". You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ('protect_me_', 'also_protect_')`. '''`` While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, an error _is_ raised if there is an actual collision with an existing attribute: `from pydantic import BaseModel, ConfigDict try: class Model(BaseModel): model_validate: str model_config = ConfigDict(protected_namespaces=('model_',)) except NameError as e: print(e) ''' Field "model_validate" conflicts with member > of protected namespace "model_". '''` ### hide\_input\_in\_errors `instance-attribute` [¶](#pydantic.config.ConfigDict.hide_input_in_errors "Permanent link") `hide_input_in_errors: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to hide inputs when printing errors. Defaults to `False`. Pydantic shows the input value and type when it raises `ValidationError` during the validation. `from pydantic import BaseModel, ValidationError class Model(BaseModel): a: str try: Model(a=123) except ValidationError as e: print(e) ''' 1 validation error for Model a Input should be a valid string [type=string_type, input_value=123, input_type=int] '''` You can hide the input value and type by setting the `hide_input_in_errors` config to `True`. `from pydantic import BaseModel, ConfigDict, ValidationError class Model(BaseModel): a: str model_config = ConfigDict(hide_input_in_errors=True) try: Model(a=123) except ValidationError as e: print(e) ''' 1 validation error for Model a Input should be a valid string [type=string_type] '''` ### defer\_build `instance-attribute` [¶](#pydantic.config.ConfigDict.defer_build "Permanent link") `defer_build: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether to defer model validator and serializer construction until the first model validation. Defaults to False. This can be useful to avoid the overhead of building models which are only used nested within other models, or when you want to manually define type namespace via [`Model.model_rebuild(_types_namespace=...)`](../base_model/#pydantic.BaseModel.model_rebuild) . Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances. ### plugin\_settings `instance-attribute` [¶](#pydantic.config.ConfigDict.plugin_settings "Permanent link") `plugin_settings: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [object](https://docs.python.org/3/glossary.html#term-object) ] | None` A `dict` of settings for plugins. Defaults to `None`. ### schema\_generator `instance-attribute` [¶](#pydantic.config.ConfigDict.schema_generator "Permanent link") `schema_generator: [type](https://docs.python.org/3/glossary.html#term-type) [GenerateSchema] | None` Warning `schema_generator` is deprecated in v2.10. Prior to v2.10, this setting was advertised as highly subject to change. It's possible that this interface may once again become public once the internal core schema generation API is more stable, but that will likely come after significant performance improvements have been made. ### json\_schema\_serialization\_defaults\_required `instance-attribute` [¶](#pydantic.config.ConfigDict.json_schema_serialization_defaults_required "Permanent link") `json_schema_serialization_defaults_required: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`. This ensures that the serialization schema will reflect the fact a field with a default will always be present when serializing the model, even though it is not required for validation. However, there are scenarios where this may be undesirable — in particular, if you want to share the schema between validation and serialization, and don't mind fields with defaults being marked as not required during serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details. `from pydantic import BaseModel, ConfigDict class Model(BaseModel): a: str = 'a' model_config = ConfigDict(json_schema_serialization_defaults_required=True) print(Model.model_json_schema(mode='validation')) ''' { 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}}, 'title': 'Model', 'type': 'object', } ''' print(Model.model_json_schema(mode='serialization')) ''' { 'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}}, 'required': ['a'], 'title': 'Model', 'type': 'object', } '''` ### json\_schema\_mode\_override `instance-attribute` [¶](#pydantic.config.ConfigDict.json_schema_mode_override "Permanent link") `json_schema_mode_override: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [ "validation", "serialization", None ]` If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to the function call. Defaults to `None`. This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the validation schema. It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation and serialization that must both be referenced from the same schema; when this happens, we automatically append `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes from being added to the definition references. `from pydantic import BaseModel, ConfigDict, Json class Model(BaseModel): a: Json[int] # requires a string to validate, but will dump an int print(Model.model_json_schema(mode='serialization')) ''' { 'properties': {'a': {'title': 'A', 'type': 'integer'}}, 'required': ['a'], 'title': 'Model', 'type': 'object', } ''' class ForceInputModel(Model): # the following ensures that even with mode='serialization', we # will get the schema that would be generated for validation. model_config = ConfigDict(json_schema_mode_override='validation') print(ForceInputModel.model_json_schema(mode='serialization')) ''' { 'properties': { 'a': { 'contentMediaType': 'application/json', 'contentSchema': {'type': 'integer'}, 'title': 'A', 'type': 'string', } }, 'required': ['a'], 'title': 'ForceInputModel', 'type': 'object', } '''` ### coerce\_numbers\_to\_str `instance-attribute` [¶](#pydantic.config.ConfigDict.coerce_numbers_to_str "Permanent link") `coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool)` If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`. Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default. `from decimal import Decimal from pydantic import BaseModel, ConfigDict, ValidationError class Model(BaseModel): value: str try: print(Model(value=42)) except ValidationError as e: print(e) ''' 1 validation error for Model value Input should be a valid string [type=string_type, input_value=42, input_type=int] ''' class Model(BaseModel): model_config = ConfigDict(coerce_numbers_to_str=True) value: str repr(Model(value=42).value) #> "42" repr(Model(value=42.13).value) #> "42.13" repr(Model(value=Decimal('42.13')).value) #> "42.13"` ### regex\_engine `instance-attribute` [¶](#pydantic.config.ConfigDict.regex_engine "Permanent link") `regex_engine: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['rust-regex', 'python-re']` The regex engine to be used for pattern validation. Defaults to `'rust-regex'`. * `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features. * `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module, which supports all regex features, but may be slower. Note If you use a compiled regex pattern, the python-re engine will be used regardless of this setting. This is so that flags such as `re.IGNORECASE` are respected. `from pydantic import BaseModel, ConfigDict, Field, ValidationError class Model(BaseModel): model_config = ConfigDict(regex_engine='python-re') value: str = Field(pattern=r'^abc(?=def)') print(Model(value='abcdef').value) #> abcdef try: print(Model(value='abxyzcdef')) except ValidationError as e: print(e) ''' 1 validation error for Model value String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str] '''` ### validation\_error\_cause `instance-attribute` [¶](#pydantic.config.ConfigDict.validation_error_cause "Permanent link") `validation_error_cause: [bool](https://docs.python.org/3/library/functions.html#bool)` If `True`, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to `False`. Note Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`. Note The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only. ### use\_attribute\_docstrings `instance-attribute` [¶](#pydantic.config.ConfigDict.use_attribute_docstrings "Permanent link") `use_attribute_docstrings: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether docstrings of attributes (bare string literals immediately following the attribute declaration) should be used for field descriptions. Defaults to `False`. Available in Pydantic v2.7+. `from pydantic import BaseModel, ConfigDict, Field class Model(BaseModel): model_config = ConfigDict(use_attribute_docstrings=True) x: str """ Example of an attribute docstring """ y: int = Field(description="Description in Field") """ Description in Field overrides attribute docstring """ print(Model.model_fields["x"].description) # > Example of an attribute docstring print(Model.model_fields["y"].description) # > Description in Field` This requires the source code of the class to be available at runtime. Usage with `TypedDict` and stdlib dataclasses Due to current limitations, attribute docstrings detection may not work as expected when using [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) and stdlib dataclasses, in particular when: * inheritance is being used. * multiple classes have the same name in the same source file. ### cache\_strings `instance-attribute` [¶](#pydantic.config.ConfigDict.cache_strings "Permanent link") `cache_strings: [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['all', 'keys', 'none']` Whether to cache strings to avoid constructing new Python objects. Defaults to True. Enabling this setting should significantly improve validation performance while increasing memory usage slightly. * `True` or `'all'` (the default): cache all strings * `'keys'`: cache only dictionary keys * `False` or `'none'`: no caching Note `True` or `'all'` is required to cache strings during general validation because validators don't know if they're in a key or a value. Tip If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage, as the performance difference is minimal if repeated strings are rare. ### validate\_by\_alias `instance-attribute` [¶](#pydantic.config.ConfigDict.validate_by_alias "Permanent link") `validate_by_alias: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether an aliased field may be populated by its alias. Defaults to `True`. Note In v2.11, `validate_by_alias` was introduced in conjunction with [`validate_by_name`](#pydantic.config.ConfigDict.validate_by_name) to empower users with more fine grained validation control. In my_field='foo'` 1. The field `'my_field'` has an alias `'my_alias'`. 2. The model can only be populated by the attribute name `'my_field'`. Warning You cannot set both `validate_by_alias` and `validate_by_name` to `False`. This would make it impossible to populate an attribute. See [usage errors](../../errors/usage_errors/#validate-by-alias-and-name-false) for an example. If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets `validate_by_name` to `True` to ensure that validation can still occur. ### validate\_by\_name `instance-attribute` [¶](#pydantic.config.ConfigDict.validate_by_name "Permanent link") `validate_by_name: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether an aliased field may be populated by its name as given by the model attribute. Defaults to `False`. Note In v2.0-v2.10, the `populate_by_name` configuration setting was used to specify whether or not a field could be populated by its name **and** alias. In v2.11, `validate_by_name` was introduced in conjunction with [`validate_by_alias`](#pydantic.config.ConfigDict.validate_by_alias) to empower users with more fine grained validation behavior control. `from pydantic import BaseModel, ConfigDict, Field class Model(BaseModel): model_config = ConfigDict(validate_by_name=True, validate_by_alias=True) my_field: str = Field(validation_alias='my_alias') # (1)! m = Model(my_alias='foo') # (2)! print(m) #> my_field='foo' m = Model(my_field='foo') # (3)! print(m) #> my_field='foo'` 1. The field `'my_field'` has an alias `'my_alias'`. 2. The model is populated by the alias `'my_alias'`. 3. The model is populated by the attribute name `'my_field'`. Warning You cannot set both `validate_by_alias` and `validate_by_name` to `False`. This would make it impossible to populate an attribute. See [usage errors](../../errors/usage_errors/#validate-by-alias-and-name-false) for an example. ### serialize\_by\_alias `instance-attribute` [¶](#pydantic.config.ConfigDict.serialize_by_alias "Permanent link") `serialize_by_alias: [bool](https://docs.python.org/3/library/functions.html#bool)` Whether an aliased field should be serialized by its alias. Defaults to `False`. Note: In v2.11, `serialize_by_alias` was introduced to address the [popular request](https://github.com/pydantic/pydantic/issues/8379) for consistency with alias behavior for validation and serialization settings. In v3, the default value is expected to change to `True` for consistency with the validation default. `from pydantic import BaseModel, ConfigDict, Field class Model(BaseModel): model_config = ConfigDict(serialize_by_alias=True) my_field: str = Field(serialization_alias='my_alias') # (1)! m = Model(my_field='foo') print(m.model_dump()) # (2)! #> {'my_alias': 'foo'}` 1. The field `'my_field'` has an alias `'my_alias'`. 2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute. with\_config [¶](#pydantic.config.with_config "Permanent link") ---------------------------------------------------------------- `with_config( *, config: [ConfigDict](#pydantic.config.ConfigDict "pydantic.config.ConfigDict") ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_TypeT], _TypeT]` `with_config( config: [ConfigDict](#pydantic.config.ConfigDict "pydantic.config.ConfigDict") , ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_TypeT], _TypeT]` `with_config( **config: Unpack[[ConfigDict](#pydantic.config.ConfigDict "pydantic.config.ConfigDict") ], ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_TypeT], _TypeT]` `with_config( config: [ConfigDict](#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | None = None, /, **kwargs: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_TypeT], _TypeT]` Usage Documentation [Configuration with other types](../../concepts/config/#configuration-on-other-supported-types) A convenience decorator to set a [Pydantic configuration](./) on a `TypedDict` or a `dataclass` from the standard library. Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers, especially with `TypedDict`. Usage `from typing_extensions import TypedDict from pydantic import ConfigDict, TypeAdapter, with_config @with_config(ConfigDict(str_to_lower=True)) class TD(TypedDict): x: str ta = TypeAdapter(TD) print(ta.validate_python({'x': 'ABC'})) #> {'x': 'abc'}` Source code in `pydantic/config.py` | | | | --- | --- | | 1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210 | ``def with_config(config: ConfigDict \| None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]: """!!! abstract "Usage Documentation" [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types) A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library. Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers, especially with `TypedDict`. !!! example "Usage" ```python from typing_extensions import TypedDict from pydantic import ConfigDict, TypeAdapter, with_config @with_config(ConfigDict(str_to_lower=True)) class TD(TypedDict): x: str ta = TypeAdapter(TD) print(ta.validate_python({'x': 'ABC'})) #> {'x': 'abc'} ``` """ if config is not None and kwargs: raise ValueError('Cannot specify both `config` and keyword arguments') if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None: warnings.warn( 'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead', category=PydanticDeprecatedSince211, stacklevel=2, ) final_config = cast(ConfigDict, kwargs_conf) else: final_config = config if config is not None else cast(ConfigDict, kwargs) def inner(class_: _TypeT, /) -> _TypeT: # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass. # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid # common mistakes, we at least check for `class_` to not be a Pydantic model. from ._internal._utils import is_model_class if is_model_class(class_): raise PydanticUserError( f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model', code='with-config-on-model', ) class_.__pydantic_config__ = final_config return class_ return inner`` | ExtraValues `module-attribute` [¶](#pydantic.config.ExtraValues "Permanent link") ---------------------------------------------------------------------------------- `ExtraValues = [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['allow', 'ignore', 'forbid']` pydantic.alias\_generators [¶](#pydantic.alias_generators "Permanent link") ---------------------------------------------------------------------------- Alias generators for converting between different capitalization conventions. ### to\_pascal [¶](#pydantic.alias_generators.to_pascal "Permanent link") `to_pascal(snake: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Convert a snake\_case string to PascalCase. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `snake` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The string to convert. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The PascalCase string. | Source code in `pydantic/alias_generators.py` | | | | --- | --- | | 12
13
14
15
16
17
18
19
20
21
22 | `def to_pascal(snake: str) -> str: """Convert a snake_case string to PascalCase. Args: snake: The string to convert. Returns: The PascalCase string. """ camel = snake.title() return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)` | ### to\_camel [¶](#pydantic.alias_generators.to_camel "Permanent link") `to_camel(snake: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Convert a snake\_case string to camelCase. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `snake` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The string to convert. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The converted camelCase string. | Source code in `pydantic/alias_generators.py` | | | | --- | --- | | 25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 | `def to_camel(snake: str) -> str: """Convert a snake_case string to camelCase. Args: snake: The string to convert. Returns: The converted camelCase string. """ # If the string is already in camelCase and does not contain a digit followed # by a lowercase letter, return it as it is if re.match('^[a-z]+[A-Za-z0-9]*$', snake) and not re.search(r'\d[a-z]', snake): return snake camel = to_pascal(snake) return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)` | ### to\_snake [¶](#pydantic.alias_generators.to_snake "Permanent link") `to_snake(camel: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Convert a PascalCase, camelCase, or kebab-case string to snake\_case. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `camel` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The string to convert. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The converted string in snake\_case. | Source code in `pydantic/alias_generators.py` | | | | --- | --- | | 43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 | `def to_snake(camel: str) -> str: """Convert a PascalCase, camelCase, or kebab-case string to snake_case. Args: camel: The string to convert. Returns: The converted string in snake_case. """ # Handle the sequence of uppercase letters followed by a lowercase letter snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel) # Insert an underscore between a lowercase letter and an uppercase letter snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) # Insert an underscore between a digit and an uppercase letter snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) # Insert an underscore between a lowercase letter and a digit snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) # Replace hyphens with underscores to handle kebab-case snake = snake.replace('-', '_') return snake.lower()` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Errors - Pydantic Errors ====== Pydantic-specific errors. PydanticErrorMixin [¶](#pydantic.errors.PydanticErrorMixin "Permanent link") ----------------------------------------------------------------------------- `PydanticErrorMixin( message: [str](https://docs.python.org/3/library/stdtypes.html#str) , *, code: PydanticErrorCodes | None )` A mixin class for common functionality shared by all Pydantic-specific errors. Attributes: | Name | Type | Description | | --- | --- | --- | | `message` | | A message describing the error. | | `code` | | An optional error code from PydanticErrorCodes enum. | Source code in `pydantic/errors.py` | | | | --- | --- | | 91
92
93 | `def __init__(self, message: str, *, code: PydanticErrorCodes \| None) -> None: self.message = message self.code = code` | PydanticUserError [¶](#pydantic.errors.PydanticUserError "Permanent link") --------------------------------------------------------------------------- `PydanticUserError( message: [str](https://docs.python.org/3/library/stdtypes.html#str) , *, code: PydanticErrorCodes | None )` Bases: `[PydanticErrorMixin](#pydantic.errors.PydanticErrorMixin "pydantic.errors.PydanticErrorMixin") `, `[TypeError](https://docs.python.org/3/library/exceptions.html#TypeError) ` An error raised due to incorrect use of Pydantic. Source code in `pydantic/errors.py` | | | | --- | --- | | 91
92
93 | `def __init__(self, message: str, *, code: PydanticErrorCodes \| None) -> None: self.message = message self.code = code` | PydanticUndefinedAnnotation [¶](#pydantic.errors.PydanticUndefinedAnnotation "Permanent link") ----------------------------------------------------------------------------------------------- `PydanticUndefinedAnnotation(name: [str](https://docs.python.org/3/library/stdtypes.html#str) , message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[PydanticErrorMixin](#pydantic.errors.PydanticErrorMixin "pydantic.errors.PydanticErrorMixin") `, `[NameError](https://docs.python.org/3/library/exceptions.html#NameError) ` A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation. Attributes: | Name | Type | Description | | --- | --- | --- | | `name` | | Name of the error. | | `message` | | Description of the error. | Source code in `pydantic/errors.py` | | | | --- | --- | | 114
115
116 | `def __init__(self, name: str, message: str) -> None: self.name = name super().__init__(message=message, code='undefined-annotation')` | ### from\_name\_error `classmethod` [¶](#pydantic.errors.PydanticUndefinedAnnotation.from_name_error "Permanent link") `from_name_error(name_error: [NameError](https://docs.python.org/3/library/exceptions.html#NameError) ) -> Self` Convert a `NameError` to a `PydanticUndefinedAnnotation` error. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `name_error` | `[NameError](https://docs.python.org/3/library/exceptions.html#NameError) ` | `NameError` to be converted. | _required_ | Returns: | Type | Description | | --- | --- | | `Self` | Converted `PydanticUndefinedAnnotation` error. | Source code in `pydantic/errors.py` | | | | --- | --- | | 118
119
120
121
122
123
124
125
126
127
128
129
130
131
132 | ``@classmethod def from_name_error(cls, name_error: NameError) -> Self: """Convert a `NameError` to a `PydanticUndefinedAnnotation` error. Args: name_error: `NameError` to be converted. Returns: Converted `PydanticUndefinedAnnotation` error. """ try: name = name_error.name # type: ignore # python > 3.10 except AttributeError: name = re.search(r".*'(.+?)'", str(name_error)).group(1) # type: ignore[union-attr] return cls(name=name, message=str(name_error))`` | PydanticImportError [¶](#pydantic.errors.PydanticImportError "Permanent link") ------------------------------------------------------------------------------- `PydanticImportError(message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[PydanticErrorMixin](#pydantic.errors.PydanticErrorMixin "pydantic.errors.PydanticErrorMixin") `, `[ImportError](https://docs.python.org/3/library/exceptions.html#ImportError) ` An error raised when an import fails due to module changes between V1 and V2. Attributes: | Name | Type | Description | | --- | --- | --- | | `message` | | Description of the error. | Source code in `pydantic/errors.py` | | | | --- | --- | | 142
143 | `def __init__(self, message: str) -> None: super().__init__(message, code='import-error')` | PydanticSchemaGenerationError [¶](#pydantic.errors.PydanticSchemaGenerationError "Permanent link") --------------------------------------------------------------------------------------------------- `PydanticSchemaGenerationError(message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[PydanticUserError](#pydantic.errors.PydanticUserError "pydantic.errors.PydanticUserError") ` An error raised during failures to generate a `CoreSchema` for some type. Attributes: | Name | Type | Description | | --- | --- | --- | | `message` | | Description of the error. | Source code in `pydantic/errors.py` | | | | --- | --- | | 153
154 | `def __init__(self, message: str) -> None: super().__init__(message, code='schema-for-unknown-type')` | PydanticInvalidForJsonSchema [¶](#pydantic.errors.PydanticInvalidForJsonSchema "Permanent link") ------------------------------------------------------------------------------------------------- `PydanticInvalidForJsonSchema(message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[PydanticUserError](#pydantic.errors.PydanticUserError "pydantic.errors.PydanticUserError") ` An error raised during failures to generate a JSON schema for some `CoreSchema`. Attributes: | Name | Type | Description | | --- | --- | --- | | `message` | | Description of the error. | Source code in `pydantic/errors.py` | | | | --- | --- | | 164
165 | `def __init__(self, message: str) -> None: super().__init__(message, code='invalid-for-json-schema')` | PydanticForbiddenQualifier [¶](#pydantic.errors.PydanticForbiddenQualifier "Permanent link") --------------------------------------------------------------------------------------------- `PydanticForbiddenQualifier( qualifier: Qualifier, annotation: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") )` Bases: `[PydanticUserError](#pydantic.errors.PydanticUserError "pydantic.errors.PydanticUserError") ` An error raised if a forbidden type qualifier is found in a type annotation. Source code in `pydantic/errors.py` | | | | --- | --- | | 180
181
182
183
184
185
186
187 | `def __init__(self, qualifier: Qualifier, annotation: Any) -> None: super().__init__( message=( f'The annotation {_repr.display_as_type(annotation)!r} contains the {self._qualifier_repr_map[qualifier]!r} ' f'type qualifier, which is invalid in the context it is defined.' ), code=None, )` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Pydantic Dataclasses - Pydantic Pydantic Dataclasses ==================== Provide an enhanced dataclass that performs validation. dataclass [¶](#pydantic.dataclasses.dataclass "Permanent link") ---------------------------------------------------------------- `dataclass( *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, eq: [bool](https://docs.python.org/3/library/functions.html#bool) = True, order: [bool](https://docs.python.org/3/library/functions.html#bool) = False, unsafe_hash: [bool](https://docs.python.org/3/library/functions.html#bool) = False, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) = False, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] | None = None, validate_on_init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) = ..., slots: [bool](https://docs.python.org/3/library/functions.html#bool) = ... ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[type](https://docs.python.org/3/glossary.html#term-type) [_T]], [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]]` `dataclass( _cls: [type](https://docs.python.org/3/glossary.html#term-type) [_T], *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, eq: [bool](https://docs.python.org/3/library/functions.html#bool) = True, order: [bool](https://docs.python.org/3/library/functions.html#bool) = False, unsafe_hash: [bool](https://docs.python.org/3/library/functions.html#bool) = False, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] | None = None, validate_on_init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) = ..., slots: [bool](https://docs.python.org/3/library/functions.html#bool) = ... ) -> [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]` `dataclass( *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, eq: [bool](https://docs.python.org/3/library/functions.html#bool) = True, order: [bool](https://docs.python.org/3/library/functions.html#bool) = False, unsafe_hash: [bool](https://docs.python.org/3/library/functions.html#bool) = False, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] | None = None, validate_on_init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[type](https://docs.python.org/3/glossary.html#term-type) [_T]], [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]]` `dataclass( _cls: [type](https://docs.python.org/3/glossary.html#term-type) [_T], *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, eq: [bool](https://docs.python.org/3/library/functions.html#bool) = True, order: [bool](https://docs.python.org/3/library/functions.html#bool) = False, unsafe_hash: [bool](https://docs.python.org/3/library/functions.html#bool) = False, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] | None = None, validate_on_init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]` `dataclass( _cls: [type](https://docs.python.org/3/glossary.html#term-type) [_T] | None = None, *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, eq: [bool](https://docs.python.org/3/library/functions.html#bool) = True, order: [bool](https://docs.python.org/3/library/functions.html#bool) = False, unsafe_hash: [bool](https://docs.python.org/3/library/functions.html#bool) = False, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] | None = None, validate_on_init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) = False, slots: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[type](https://docs.python.org/3/glossary.html#term-type) [_T]], [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]] | [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass] )` Usage Documentation [`dataclasses`](../../concepts/dataclasses/) A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`, but with added validation. This function should be used similarly to `dataclasses.dataclass`. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `_cls` | `[type](https://docs.python.org/3/glossary.html#term-type) [_T] \| None` | The target `dataclass`. | `None` | | `init` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False]` | Included for signature compatibility with `dataclasses.dataclass`, and is passed through to `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its own `__init__` function. | `False` | | `repr` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | A boolean indicating whether to include the field in the `__repr__` output. | `True` | | `eq` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Determines if a `__eq__` method should be generated for the class. | `True` | | `order` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`. | `False` | | `unsafe_hash` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`. | `False` | | `frozen` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise). | `None` | | `config` | `[ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") \| [type](https://docs.python.org/3/glossary.html#term-type) [[object](https://docs.python.org/3/glossary.html#term-object) ] \| None` | The Pydantic config to use for the `dataclass`. | `None` | | `validate_on_init` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses are validated on init. | `None` | | `kw_only` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`. | `False` | | `slots` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of new attributes after instantiation. | `False` | Returns: | Type | Description | | --- | --- | | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[type](https://docs.python.org/3/glossary.html#term-type) [_T]], [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]] \| [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]` | A decorator that accepts a class as its argument and returns a Pydantic `dataclass`. | Raises: | Type | Description | | --- | --- | | `[AssertionError](https://docs.python.org/3/library/exceptions.html#AssertionError) ` | Raised if `init` is not `False` or `validate_on_init` is `False`. | Source code in `pydantic/dataclasses.py` | | | | --- | --- | | 97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282 | ``@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) def dataclass( _cls: type[_T] \| None = None, *, init: Literal[False] = False, repr: bool = True, eq: bool = True, order: bool = False, unsafe_hash: bool = False, frozen: bool \| None = None, config: ConfigDict \| type[object] \| None = None, validate_on_init: bool \| None = None, kw_only: bool = False, slots: bool = False, ) -> Callable[[type[_T]], type[PydanticDataclass]] \| type[PydanticDataclass]: """!!! abstract "Usage Documentation" [`dataclasses`](../concepts/dataclasses.md) A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`, but with added validation. This function should be used similarly to `dataclasses.dataclass`. Args: _cls: The target `dataclass`. init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its own `__init__` function. repr: A boolean indicating whether to include the field in the `__repr__` output. eq: Determines if a `__eq__` method should be generated for the class. order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`. unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`. frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise). config: The Pydantic config to use for the `dataclass`. validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses are validated on init. kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`. slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of new attributes after instantiation. Returns: A decorator that accepts a class as its argument and returns a Pydantic `dataclass`. Raises: AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`. """ assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' assert validate_on_init is not False, 'validate_on_init=False is no longer supported' if sys.version_info >= (3, 10): kwargs = {'kw_only': kw_only, 'slots': slots} else: kwargs = {} def make_pydantic_fields_compatible(cls: type[Any]) -> None: """Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only` To do that, we simply change `x: int = pydantic.Field(..., kw_only=True)` into `x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)` """ for annotation_cls in cls.__mro__: annotations: dict[str, Any] = getattr(annotation_cls, '__annotations__', {}) for field_name in annotations: field_value = getattr(cls, field_name, None) # Process only if this is an instance of `FieldInfo`. if not isinstance(field_value, FieldInfo): continue # Initialize arguments for the standard `dataclasses.field`. field_args: dict = {'default': field_value} # Handle `kw_only` for Python 3.10+ if sys.version_info >= (3, 10) and field_value.kw_only: field_args['kw_only'] = True # Set `repr` attribute if it's explicitly specified to be not `True`. if field_value.repr is not True: field_args['repr'] = field_value.repr setattr(cls, field_name, dataclasses.field(**field_args)) # In Python 3.9, when subclassing, information is pulled from cls.__dict__['__annotations__'] # for annotations, so we must make sure it's initialized before we add to it. if cls.__dict__.get('__annotations__') is None: cls.__annotations__ = {} cls.__annotations__[field_name] = annotations[field_name] def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: """Create a Pydantic dataclass from a regular dataclass. Args: cls: The class to create the Pydantic dataclass from. Returns: A Pydantic dataclass. """ from ._internal._utils import is_model_class if is_model_class(cls): raise PydanticUserError( f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model', code='dataclass-on-model', ) original_cls = cls # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__) if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'): warn( f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. ' f'The `config` specification from `dataclass` decorator will take priority.', category=UserWarning, stacklevel=2, ) # if config is not explicitly provided, try to read it from the type config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None) config_wrapper = _config.ConfigWrapper(config_dict) decorators = _decorators.DecoratorInfos.build(cls) # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description, # since dataclasses.dataclass will set this as the __doc__ original_doc = cls.__doc__ if _pydantic_dataclasses.is_builtin_dataclass(cls): # Don't preserve the docstring for vanilla dataclasses, as it may include the signature # This matches v1 behavior, and there was an explicit test for it original_doc = None # We don't want to add validation to the existing std lib dataclass, so we will subclass it # If the class is generic, we need to make sure the subclass also inherits from Generic # with all the same parameters. bases = (cls,) if issubclass(cls, Generic): generic_base = Generic[cls.__parameters__] # type: ignore bases = bases + (generic_base,) cls = types.new_class(cls.__name__, bases) make_pydantic_fields_compatible(cls) # Respect frozen setting from dataclass constructor and fallback to config setting if not provided if frozen is not None: frozen_ = frozen if config_wrapper.frozen: # It's not recommended to define both, as the setting from the dataclass decorator will take priority. warn( f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.' 'This is not recommended. The `frozen` specification on `dataclass` will take priority.', category=UserWarning, stacklevel=2, ) else: frozen_ = config_wrapper.frozen or False cls = dataclasses.dataclass( # type: ignore[call-overload] cls, # the value of init here doesn't affect anything except that it makes it easier to generate a signature init=True, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen_, **kwargs, ) # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses. # It should be set as early as possible: cls.__is_pydantic_dataclass__ = True cls.__pydantic_decorators__ = decorators # type: ignore cls.__doc__ = original_doc cls.__module__ = original_cls.__module__ cls.__qualname__ = original_cls.__qualname__ cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful. # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models: # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function), # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models). _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False) return cls return create_dataclass if _cls is None else create_dataclass(_cls)`` | rebuild\_dataclass [¶](#pydantic.dataclasses.rebuild_dataclass "Permanent link") --------------------------------------------------------------------------------- `rebuild_dataclass( cls: [type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass], *, force: [bool](https://docs.python.org/3/library/functions.html#bool) = False, raise_errors: [bool](https://docs.python.org/3/library/functions.html#bool) = True, _parent_namespace_depth: [int](https://docs.python.org/3/library/functions.html#int) = 2, _types_namespace: MappingNamespace | None = None ) -> [bool](https://docs.python.org/3/library/functions.html#bool) | None` Try to rebuild the pydantic-core schema for the dataclass. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. This is analogous to `BaseModel.model_rebuild`. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `cls` | `[type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]` | The class to rebuild the pydantic-core schema for. | _required_ | | `force` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to force the rebuilding of the schema, defaults to `False`. | `False` | | `raise_errors` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to raise errors, defaults to `True`. | `True` | | `_parent_namespace_depth` | `[int](https://docs.python.org/3/library/functions.html#int) ` | The depth level of the parent namespace, defaults to 2. | `2` | | `_types_namespace` | `MappingNamespace \| None` | The types namespace, defaults to `None`. | `None` | Returns: | Type | Description | | --- | --- | | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Returns `None` if the schema is already "complete" and rebuilding was not required. | | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. | Source code in `pydantic/dataclasses.py` | | | | --- | --- | | 301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359 | ``def rebuild_dataclass( cls: type[PydanticDataclass], *, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace \| None = None, ) -> bool \| None: """Try to rebuild the pydantic-core schema for the dataclass. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. This is analogous to `BaseModel.model_rebuild`. Args: cls: The class to rebuild the pydantic-core schema for. force: Whether to force the rebuilding of the schema, defaults to `False`. raise_errors: Whether to raise errors, defaults to `True`. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. _types_namespace: The types namespace, defaults to `None`. Returns: Returns `None` if the schema is already "complete" and rebuilding was not required. If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. """ if not force and cls.__pydantic_complete__: return None for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): if attr in cls.__dict__: # Deleting the validator/serializer is necessary as otherwise they can get reused in # pydantic-core. Same applies for the core schema that can be reused in schema generation. delattr(cls, attr) cls.__pydantic_complete__ = False if _types_namespace is not None: rebuild_ns = _types_namespace elif _parent_namespace_depth > 0: rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} else: rebuild_ns = {} ns_resolver = _namespace_utils.NsResolver( parent_namespace=rebuild_ns, ) return _pydantic_dataclasses.complete_dataclass( cls, _config.ConfigWrapper(cls.__pydantic_config__, check=False), raise_errors=raise_errors, ns_resolver=ns_resolver, # We could provide a different config instead (with `'defer_build'` set to `True`) # of this explicit `_force_build` argument, but because config can come from the # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass` # will overwrite `__pydantic_config__` with the provided config above: _force_build=True, )`` | is\_pydantic\_dataclass [¶](#pydantic.dataclasses.is_pydantic_dataclass "Permanent link") ------------------------------------------------------------------------------------------ `is_pydantic_dataclass( class_: [type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ) -> TypeGuard[[type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]]` Whether a class is a pydantic dataclass. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `class_` | `[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | The class. | _required_ | Returns: | Type | Description | | --- | --- | | `TypeGuard[[type](https://docs.python.org/3/glossary.html#term-type) [PydanticDataclass]]` | `True` if the class is a pydantic dataclass, `False` otherwise. | Source code in `pydantic/dataclasses.py` | | | | --- | --- | | 362
363
364
365
366
367
368
369
370
371
372
373
374 | ``def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]: """Whether a class is a pydantic dataclass. Args: class_: The class. Returns: `True` if the class is a pydantic dataclass, `False` otherwise. """ try: return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_) except AttributeError: return False`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Experimental - Pydantic Pipeline API[¶](#pipeline-api "Permanent link") ================================================ Experimental pipeline API functionality. Be careful with this API, it's subject to change. \_Pipeline `dataclass` [¶](#pydantic.experimental.pipeline._Pipeline "Permanent link") --------------------------------------------------------------------------------------- `_Pipeline(_steps: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [_Step, ...])` Bases: `[Generic](https://docs.python.org/3/library/typing.html#typing.Generic "typing.Generic") [_InT, _OutT]` Abstract representation of a chain of validation, transformation, and parsing steps. ### transform [¶](#pydantic.experimental.pipeline._Pipeline.transform "Permanent link") `transform( func: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_OutT], _NewOutT] ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` Transform the output of the previous step. If used as the first step in a pipeline, the type of the field is used. That is, the transformation is applied to after the value is parsed to the field's type. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 134
135
136
137
138
139
140
141
142
143 | `def transform( self, func: Callable[[_OutT], _NewOutT], ) -> _Pipeline[_InT, _NewOutT]: """Transform the output of the previous step. If used as the first step in a pipeline, the type of the field is used. That is, the transformation is applied to after the value is parsed to the field's type. """ return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))` | ### validate\_as [¶](#pydantic.experimental.pipeline._Pipeline.validate_as "Permanent link") `validate_as( tp: [type](https://docs.python.org/3/glossary.html#term-type) [_NewOutT], *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) = ... ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` `validate_as( tp: [EllipsisType](https://docs.python.org/3/library/types.html#types.EllipsisType "types.EllipsisType") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) = ... ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` `validate_as( tp: [type](https://docs.python.org/3/glossary.html#term-type) [_NewOutT] | [EllipsisType](https://docs.python.org/3/library/types.html#types.EllipsisType "types.EllipsisType") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Validate / parse the input into a new type. If no type is provided, the type of the field is used. Types are parsed in Pydantic's `lax` mode by default, but you can enable `strict` mode by passing `strict=True`. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 152
153
154
155
156
157
158
159
160
161
162 | ``def validate_as(self, tp: type[_NewOutT] \| EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore """Validate / parse the input into a new type. If no type is provided, the type of the field is used. Types are parsed in Pydantic's `lax` mode by default, but you can enable `strict` mode by passing `strict=True`. """ if isinstance(tp, EllipsisType): return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),)) return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))`` | ### validate\_as\_deferred [¶](#pydantic.experimental.pipeline._Pipeline.validate_as_deferred "Permanent link") `validate_as_deferred( func: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [type](https://docs.python.org/3/glossary.html#term-type) [_NewOutT]] ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` Parse the input into a new type, deferring resolution of the type until the current class is fully defined. This is useful when you need to reference the class in it's own type annotations. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 164
165
166
167
168
169
170 | `def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]: """Parse the input into a new type, deferring resolution of the type until the current class is fully defined. This is useful when you need to reference the class in it's own type annotations. """ return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))` | ### constrain [¶](#pydantic.experimental.pipeline._Pipeline.constrain "Permanent link") `constrain(constraint: Ge) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutGe]` `constrain(constraint: Gt) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutGt]` `constrain(constraint: Le) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLe]` `constrain(constraint: Lt) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLt]` `constrain(constraint: Len) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLen]` `constrain( constraint: MultipleOf, ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` `constrain( constraint: Timezone, ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutDatetime]` `constrain(constraint: Predicate) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` `constrain( constraint: Interval, ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutInterval]` `constrain(constraint: _Eq) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` `constrain(constraint: _NotEq) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` `constrain(constraint: _In) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` `constrain(constraint: _NotIn) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` `constrain( constraint: [Pattern](https://docs.python.org/3/library/re.html#re.Pattern "re.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ], ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` `constrain(constraint: _ConstraintAnnotation) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Constrain a value to meet a certain condition. We support most conditions from `annotated_types`, as well as regular expressions. Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc so you don't need to call this directly. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 223
224
225
226
227
228
229
230
231 | ``def constrain(self, constraint: _ConstraintAnnotation) -> Any: """Constrain a value to meet a certain condition. We support most conditions from `annotated_types`, as well as regular expressions. Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc so you don't need to call this directly. """ return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))`` | ### predicate [¶](#pydantic.experimental.pipeline._Pipeline.predicate "Permanent link") `predicate( func: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_NewOutT], [bool](https://docs.python.org/3/library/functions.html#bool) ] ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutT]` Constrain a value to meet a certain predicate. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 233
234
235 | `def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]: """Constrain a value to meet a certain predicate.""" return self.constrain(annotated_types.Predicate(func))` | ### gt [¶](#pydantic.experimental.pipeline._Pipeline.gt "Permanent link") `gt(gt: _NewOutGt) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutGt]` Constrain a value to be greater than a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 237
238
239 | `def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]: """Constrain a value to be greater than a certain value.""" return self.constrain(annotated_types.Gt(gt))` | ### lt [¶](#pydantic.experimental.pipeline._Pipeline.lt "Permanent link") `lt(lt: _NewOutLt) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLt]` Constrain a value to be less than a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 241
242
243 | `def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]: """Constrain a value to be less than a certain value.""" return self.constrain(annotated_types.Lt(lt))` | ### ge [¶](#pydantic.experimental.pipeline._Pipeline.ge "Permanent link") `ge(ge: _NewOutGe) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutGe]` Constrain a value to be greater than or equal to a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 245
246
247 | `def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]: """Constrain a value to be greater than or equal to a certain value.""" return self.constrain(annotated_types.Ge(ge))` | ### le [¶](#pydantic.experimental.pipeline._Pipeline.le "Permanent link") `le(le: _NewOutLe) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLe]` Constrain a value to be less than or equal to a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 249
250
251 | `def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]: """Constrain a value to be less than or equal to a certain value.""" return self.constrain(annotated_types.Le(le))` | ### len [¶](#pydantic.experimental.pipeline._Pipeline.len "Permanent link") `len( min_len: [int](https://docs.python.org/3/library/functions.html#int) , max_len: [int](https://docs.python.org/3/library/functions.html#int) | None = None ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutLen]` Constrain a value to have a certain length. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 253
254
255 | `def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int \| None = None) -> _Pipeline[_InT, _NewOutLen]: """Constrain a value to have a certain length.""" return self.constrain(annotated_types.Len(min_len, max_len))` | ### multiple\_of [¶](#pydantic.experimental.pipeline._Pipeline.multiple_of "Permanent link") `multiple_of( multiple_of: _NewOutDiv, ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutDiv]` `multiple_of( multiple_of: _NewOutMod, ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _NewOutMod]` `multiple_of(multiple_of: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Constrain a value to be a multiple of a certain number. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 263
264
265 | `def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]: """Constrain a value to be a multiple of a certain number.""" return self.constrain(annotated_types.MultipleOf(multiple_of))` | ### eq [¶](#pydantic.experimental.pipeline._Pipeline.eq "Permanent link") `eq(value: _OutT) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` Constrain a value to be equal to a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 267
268
269 | `def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: """Constrain a value to be equal to a certain value.""" return self.constrain(_Eq(value))` | ### not\_eq [¶](#pydantic.experimental.pipeline._Pipeline.not_eq "Permanent link") `not_eq(value: _OutT) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` Constrain a value to not be equal to a certain value. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 271
272
273 | `def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: """Constrain a value to not be equal to a certain value.""" return self.constrain(_NotEq(value))` | ### in\_ [¶](#pydantic.experimental.pipeline._Pipeline.in_ "Permanent link") `in_(values: [Container](https://docs.python.org/3/library/collections.abc.html#collections.abc.Container "collections.abc.Container") [_OutT]) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` Constrain a value to be in a certain set. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 275
276
277 | `def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: """Constrain a value to be in a certain set.""" return self.constrain(_In(values))` | ### not\_in [¶](#pydantic.experimental.pipeline._Pipeline.not_in "Permanent link") `not_in(values: [Container](https://docs.python.org/3/library/collections.abc.html#collections.abc.Container "collections.abc.Container") [_OutT]) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OutT]` Constrain a value to not be in a certain set. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 279
280
281 | `def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: """Constrain a value to not be in a certain set.""" return self.constrain(_NotIn(values))` | ### otherwise [¶](#pydantic.experimental.pipeline._Pipeline.otherwise "Permanent link") `otherwise( other: [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_OtherIn, _OtherOut] ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT | _OtherIn, _OutT | _OtherOut]` Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 326
327
328 | `def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT \| _OtherIn, _OutT \| _OtherOut]: """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails.""" return _Pipeline((_PipelineOr(self, other),))` | ### then [¶](#pydantic.experimental.pipeline._Pipeline.then "Permanent link") `then( other: [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_OutT, _OtherOut] ) -> [_Pipeline](#pydantic.experimental.pipeline._Pipeline "pydantic.experimental.pipeline._Pipeline") [_InT, _OtherOut]` Pipe the result of one validation chain into another. Source code in `pydantic/experimental/pipeline.py` | | | | --- | --- | | 332
333
334 | `def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]: """Pipe the result of one validation chain into another.""" return _Pipeline((_PipelineAnd(self, other),))` | Arguments schema API[¶](#arguments-schema-api "Permanent link") ================================================================ Experimental module exposing a function to generate a core schema that validates callable arguments. generate\_arguments\_schema [¶](#pydantic.experimental.arguments_schema.generate_arguments_schema "Permanent link") -------------------------------------------------------------------------------------------------------------------- `generate_arguments_schema( func: [Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], schema_type: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [ "arguments", "arguments-v3" ] = "arguments-v3", parameters_callback: ( [Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable") [[[int](https://docs.python.org/3/library/functions.html#int) , [str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["skip"] | None] | None ) = None, config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.ConfigDict") | None = None, ) -> CoreSchema` Generate the schema for the arguments of a function. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `func` | `[Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | The function to generate the schema for. | _required_ | | `schema_type` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['arguments', 'arguments-v3']` | The type of schema to generate. | `'arguments-v3'` | | `parameters_callback` | `[Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable "collections.abc.Callable") [[[int](https://docs.python.org/3/library/functions.html#int) , [str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['skip'] \| None] \| None` | A callable that will be invoked for each parameter. The callback should take three required arguments: the index, the name and the type annotation (or [`Parameter.empty`](https://docs.python.org/3/library/inspect.html#inspect.Parameter.empty)
if not annotated) of the parameter. The callback can optionally return `'skip'`, so that the parameter gets excluded from the resulting schema. | `None` | | `config` | `[ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.ConfigDict") \| None` | The configuration to use. | `None` | Returns: | Type | Description | | --- | --- | | `CoreSchema` | The generated schema. | Source code in `pydantic/experimental/arguments_schema.py` | | | | --- | --- | | 14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 | ``def generate_arguments_schema( func: Callable[..., Any], schema_type: Literal['arguments', 'arguments-v3'] = 'arguments-v3', parameters_callback: Callable[[int, str, Any], Literal['skip'] \| None] \| None = None, config: ConfigDict \| None = None, ) -> CoreSchema: """Generate the schema for the arguments of a function. Args: func: The function to generate the schema for. schema_type: The type of schema to generate. parameters_callback: A callable that will be invoked for each parameter. The callback should take three required arguments: the index, the name and the type annotation (or [`Parameter.empty`][inspect.Parameter.empty] if not annotated) of the parameter. The callback can optionally return `'skip'`, so that the parameter gets excluded from the resulting schema. config: The configuration to use. Returns: The generated schema. """ generate_schema = _generate_schema.GenerateSchema( _config.ConfigWrapper(config), ns_resolver=_namespace_utils.NsResolver(namespaces_tuple=_namespace_utils.ns_for_function(func)), ) if schema_type == 'arguments': schema = generate_schema._arguments_schema(func, parameters_callback) # pyright: ignore[reportArgumentType] else: schema = generate_schema._arguments_v3_schema(func, parameters_callback) # pyright: ignore[reportArgumentType] return generate_schema.clean_schema(schema)`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # BaseModel - Pydantic BaseModel ========= Pydantic models are simply classes which inherit from `BaseModel` and define fields as annotated attributes. pydantic.BaseModel [¶](#pydantic.BaseModel "Permanent link") ------------------------------------------------------------- Usage Documentation [Models](../../concepts/models/) A base class for creating Pydantic models. Attributes: | Name | Type | Description | | --- | --- | --- | | `__class_vars__` | `[set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` | The names of the class variables defined on the model. | | `__private_attributes__` | `[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "typing.Dict") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [ModelPrivateAttr](../fields/#pydantic.fields.ModelPrivateAttr "pydantic.fields.ModelPrivateAttr") ]` | Metadata about the private attributes of the model. | | `__signature__` | `[Signature](https://docs.python.org/3/library/inspect.html#inspect.Signature "inspect.Signature") ` | The synthesized `__init__` [`Signature`](https://docs.python.org/3/library/inspect.html#inspect.Signature)
of the model. | | `__pydantic_complete__` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether model building is completed, or if there are still undefined fields. | | `[__pydantic_core_schema__](#pydantic.BaseModel.__pydantic_core_schema__ "pydantic.BaseModel.__pydantic_core_schema__") ` | `CoreSchema` | The core schema of the model. | | `__pydantic_custom_init__` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether the model has a custom `__init__` function. | | `__pydantic_decorators__` | `DecoratorInfos` | Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. | | `__pydantic_generic_metadata__` | `PydanticGenericMetadata` | Metadata for generic models; contains data used for a similar purpose to **args**, **origin**, **parameters** in typing-module generics. May eventually be replaced by these. | | `__pydantic_parent_namespace__` | `[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "typing.Dict") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Parent namespace of the model, used for automatic rebuilding of models. | | `__pydantic_post_init__` | `None \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['model_post_init']` | The name of the post-init method for the model, if defined. | | `__pydantic_root_model__` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether the model is a [`RootModel`](../root_model/#pydantic.root_model.RootModel)
. | | `__pydantic_serializer__` | `[SchemaSerializer](../pydantic_core/#pydantic_core.SchemaSerializer "pydantic_core.SchemaSerializer") ` | The `pydantic-core` `SchemaSerializer` used to dump instances of the model. | | `__pydantic_validator__` | `[SchemaValidator](../pydantic_core/#pydantic_core.SchemaValidator "pydantic_core.SchemaValidator") \| PluggableSchemaValidator` | The `pydantic-core` `SchemaValidator` used to validate instances of the model. | | `__pydantic_fields__` | `[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "typing.Dict") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](../fields/#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ]` | A dictionary of field names and their corresponding [`FieldInfo`](../fields/#pydantic.fields.FieldInfo)
objects. | | `__pydantic_computed_fields__` | `[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "typing.Dict") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](../fields/#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ]` | A dictionary of computed field names and their corresponding [`ComputedFieldInfo`](../fields/#pydantic.fields.ComputedFieldInfo)
objects. | | `__pydantic_extra__` | `dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A dictionary containing extra values, if [`extra`](../config/#pydantic.config.ConfigDict.extra)
is set to `'allow'`. | | `__pydantic_fields_set__` | `[set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` | The names of fields explicitly set during instantiation. | | `__pydantic_private__` | `dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Values of private attributes set on the model instance. | Source code in `pydantic/main.py` | | | | --- | --- | | 121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646 | ``class BaseModel(metaclass=_model_construction.ModelMetaclass): """!!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. Attributes: __class_vars__: The names of the class variables defined on the model. __private_attributes__: Metadata about the private attributes of the model. __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model. __pydantic_complete__: Whether model building is completed, or if there are still undefined fields. __pydantic_core_schema__: The core schema of the model. __pydantic_custom_init__: Whether the model has a custom `__init__` function. __pydantic_decorators__: Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these. __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models. __pydantic_post_init__: The name of the post-init method for the model, if defined. __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel]. __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model. __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model. __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects. __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects. __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`. __pydantic_fields_set__: The names of fields explicitly set during instantiation. __pydantic_private__: Values of private attributes set on the model instance. """ # Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes. model_config: ClassVar[ConfigDict] = ConfigDict() """ Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. """ __class_vars__: ClassVar[set[str]] """The names of the class variables defined on the model.""" __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] # noqa: UP006 """Metadata about the private attributes of the model.""" __signature__: ClassVar[Signature] """The synthesized `__init__` [`Signature`][inspect.Signature] of the model.""" __pydantic_complete__: ClassVar[bool] = False """Whether model building is completed, or if there are still undefined fields.""" __pydantic_core_schema__: ClassVar[CoreSchema] """The core schema of the model.""" __pydantic_custom_init__: ClassVar[bool] """Whether the model has a custom `__init__` method.""" # Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation. __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos() """Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.""" __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] """Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.""" __pydantic_parent_namespace__: ClassVar[Dict[str, Any] \| None] = None # noqa: UP006 """Parent namespace of the model, used for automatic rebuilding of models.""" __pydantic_post_init__: ClassVar[None \| Literal['model_post_init']] """The name of the post-init method for the model, if defined.""" __pydantic_root_model__: ClassVar[bool] = False """Whether the model is a [`RootModel`][pydantic.root_model.RootModel].""" __pydantic_serializer__: ClassVar[SchemaSerializer] """The `pydantic-core` `SchemaSerializer` used to dump instances of the model.""" __pydantic_validator__: ClassVar[SchemaValidator \| PluggableSchemaValidator] """The `pydantic-core` `SchemaValidator` used to validate instances of the model.""" __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] # noqa: UP006 """A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects. This replaces `Model.__fields__` from Pydantic V1. """ __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] # noqa: UP006 """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`""" __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] # noqa: UP006 """A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.""" __pydantic_extra__: dict[str, Any] \| None = _model_construction.NoInitField(init=False) """A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`.""" __pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False) """The names of fields explicitly set during instantiation.""" __pydantic_private__: dict[str, Any] \| None = _model_construction.NoInitField(init=False) """Values of private attributes set on the model instance.""" if not TYPE_CHECKING: # Prevent `BaseModel` from being instantiated directly # (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors): __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema( 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', code='base-model-instantiated', ) __pydantic_validator__ = _mock_val_ser.MockValSer( 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', val_or_ser='validator', code='base-model-instantiated', ) __pydantic_serializer__ = _mock_val_ser.MockValSer( 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', val_or_ser='serializer', code='base-model-instantiated', ) __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' def __init__(self, /, **data: Any) -> None: """Create a new model by parsing and validating input data from keyword arguments. Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) if self is not validated_self: warnings.warn( 'A custom validator is returning a value other than `self`.\n' "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n" 'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.', stacklevel=2, ) # The following line sets a flag that we use to determine when `__init__` gets overridden by the user __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] @_utils.deprecated_instance_property @classmethod def model_fields(cls) -> dict[str, FieldInfo]: """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances. !!! warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. """ return getattr(cls, '__pydantic_fields__', {}) @_utils.deprecated_instance_property @classmethod def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]: """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances. !!! warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. """ return getattr(cls, '__pydantic_computed_fields__', {}) @property def model_extra(self) -> dict[str, Any] \| None: """Get extra fields set during validation. Returns: A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`. """ return self.__pydantic_extra__ @property def model_fields_set(self) -> set[str]: """Returns the set of fields that have been explicitly set on this model instance. Returns: A set of strings representing the fields that have been set, i.e. that were not filled from defaults. """ return self.__pydantic_fields_set__ @classmethod def model_construct(cls, _fields_set: set[str] \| None = None, **values: Any) -> Self: # noqa: C901 """Creates a new instance of the `Model` class with validated data. Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. Default values are respected, but no other validation is performed. !!! note `model_construct()` generally respects the `model_config.extra` setting on the provided model. That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in an error if extra values are passed, but they will be ignored. Args: _fields_set: A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the `values` argument will be used. values: Trusted or pre-validated data dictionary. Returns: A new instance of the `Model` class with validated data. """ m = cls.__new__(cls) fields_values: dict[str, Any] = {} fields_set = set() for name, field in cls.__pydantic_fields__.items(): if field.alias is not None and field.alias in values: fields_values[name] = values.pop(field.alias) fields_set.add(name) if (name not in fields_set) and (field.validation_alias is not None): validation_aliases: list[str \| AliasPath] = ( field.validation_alias.choices if isinstance(field.validation_alias, AliasChoices) else [field.validation_alias] ) for alias in validation_aliases: if isinstance(alias, str) and alias in values: fields_values[name] = values.pop(alias) fields_set.add(name) break elif isinstance(alias, AliasPath): value = alias.search_dict_for_path(values) if value is not PydanticUndefined: fields_values[name] = value fields_set.add(name) break if name not in fields_set: if name in values: fields_values[name] = values.pop(name) fields_set.add(name) elif not field.is_required(): fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) if _fields_set is None: _fields_set = fields_set _extra: dict[str, Any] \| None = values if cls.model_config.get('extra') == 'allow' else None _object_setattr(m, '__dict__', fields_values) _object_setattr(m, '__pydantic_fields_set__', _fields_set) if not cls.__pydantic_root_model__: _object_setattr(m, '__pydantic_extra__', _extra) if cls.__pydantic_post_init__: m.model_post_init(None) # update private attributes with values set if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: for k, v in values.items(): if k in m.__private_attributes__: m.__pydantic_private__[k] = v elif not cls.__pydantic_root_model__: # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist # Since it doesn't, that means that `__pydantic_private__` should be set to None _object_setattr(m, '__pydantic_private__', None) return m def model_copy(self, *, update: Mapping[str, Any] \| None = None, deep: bool = False) -> Self: """!!! abstract "Usage Documentation" [`model_copy`](../concepts/serialization.md#model_copy) Returns a copy of the model. !!! note The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]). Args: update: Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data. deep: Set to `True` to make a deep copy of the model. Returns: New model instance. """ copied = self.__deepcopy__() if deep else self.__copy__() if update: if self.model_config.get('extra') == 'allow': for k, v in update.items(): if k in self.__pydantic_fields__: copied.__dict__[k] = v else: if copied.__pydantic_extra__ is None: copied.__pydantic_extra__ = {} copied.__pydantic_extra__[k] = v else: copied.__dict__.update(update) copied.__pydantic_fields_set__.update(update.keys()) return copied def model_dump( self, *, mode: Literal['json', 'python'] \| str = 'python', include: IncEx \| None = None, exclude: IncEx \| None = None, context: Any \| None = None, by_alias: bool \| None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool \| Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] \| None = None, serialize_as_any: bool = False, ) -> dict[str, Any]: """!!! abstract "Usage Documentation" [`model_dump`](../concepts/serialization.md#modelmodel_dump) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Args: mode: The mode in which `to_python` should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects. include: A set of fields to include in the output. exclude: A set of fields to exclude from the output. context: Additional context to pass to the serializer. by_alias: Whether to use the field's alias in the dictionary key if defined. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of `None`. round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. fallback: A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. Returns: A dictionary representation of the model. """ return self.__pydantic_serializer__.to_python( self, mode=mode, by_alias=by_alias, include=include, exclude=exclude, context=context, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, round_trip=round_trip, warnings=warnings, fallback=fallback, serialize_as_any=serialize_as_any, ) def model_dump_json( self, *, indent: int \| None = None, include: IncEx \| None = None, exclude: IncEx \| None = None, context: Any \| None = None, by_alias: bool \| None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool \| Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] \| None = None, serialize_as_any: bool = False, ) -> str: """!!! abstract "Usage Documentation" [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) Generates a JSON representation of the model using Pydantic's `to_json` method. Args: indent: Indentation to use in the JSON output. If None is passed, the output will be compact. include: Field(s) to include in the JSON output. exclude: Field(s) to exclude from the JSON output. context: Additional context to pass to the serializer. by_alias: Whether to serialize using field aliases. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of `None`. round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. fallback: A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. Returns: A JSON string representation of the model. """ return self.__pydantic_serializer__.to_json( self, indent=indent, include=include, exclude=exclude, context=context, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, round_trip=round_trip, warnings=warnings, fallback=fallback, serialize_as_any=serialize_as_any, ).decode() @classmethod def model_json_schema( cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, mode: JsonSchemaMode = 'validation', ) -> dict[str, Any]: """Generates a JSON schema for a model class. Args: by_alias: Whether to use attribute aliases or not. ref_template: The reference template. schema_generator: To override the logic used to generate the JSON schema, as a subclass of `GenerateJsonSchema` with your desired modifications mode: The mode in which to generate the schema. Returns: The JSON schema for the given model class. """ return model_json_schema( cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode ) @classmethod def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str: """Compute the class name for parametrizations of generic classes. This method can be overridden to achieve a custom naming scheme for generic BaseModels. Args: params: Tuple of types of the class. Given a generic class `Model` with 2 type variables and a concrete model `Model[str, int]`, the value `(str, int)` would be passed to `params`. Returns: String representing the new class where `params` are passed to `cls` as type variables. Raises: TypeError: Raised when trying to generate concrete names for non-generic models. """ if not issubclass(cls, typing.Generic): raise TypeError('Concrete names should only be generated for generic models.') # Any strings received should represent forward references, so we handle them specially below. # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future, # we may be able to remove this special case. param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] params_component = ', '.join(param_names) return f'{cls.__name__}[{params_component}]' def model_post_init(self, context: Any, /) -> None: """Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. """ pass @classmethod def model_rebuild( cls, *, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace \| None = None, ) -> bool \| None: """Try to rebuild the pydantic-core schema for the model. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. Args: force: Whether to force the rebuilding of the model schema, defaults to `False`. raise_errors: Whether to raise errors, defaults to `True`. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. _types_namespace: The types namespace, defaults to `None`. Returns: Returns `None` if the schema is already "complete" and rebuilding was not required. If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. """ if not force and cls.__pydantic_complete__: return None for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): if attr in cls.__dict__: # Deleting the validator/serializer is necessary as otherwise they can get reused in # pydantic-core. Same applies for the core schema that can be reused in schema generation. delattr(cls, attr) cls.__pydantic_complete__ = False if _types_namespace is not None: rebuild_ns = _types_namespace elif _parent_namespace_depth > 0: rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} else: rebuild_ns = {} parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} ns_resolver = _namespace_utils.NsResolver( parent_namespace={**rebuild_ns, **parent_ns}, ) if not cls.__pydantic_fields_complete__: typevars_map = _generics.get_model_typevars_map(cls) try: cls.__pydantic_fields__ = _fields.rebuild_model_fields( cls, ns_resolver=ns_resolver, typevars_map=typevars_map, ) except NameError as e: exc = PydanticUndefinedAnnotation.from_name_error(e) _mock_val_ser.set_model_mocks(cls, f'`{exc.name}`') if raise_errors: raise exc from e if not raise_errors and not cls.__pydantic_fields_complete__: # No need to continue with schema gen, it is guaranteed to fail return False assert cls.__pydantic_fields_complete__ return _model_construction.complete_model_class( cls, _config.ConfigWrapper(cls.model_config, check=False), raise_errors=raise_errors, ns_resolver=ns_resolver, ) @classmethod def model_validate( cls, obj: Any, *, strict: bool \| None = None, from_attributes: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """Validate a pydantic model instance. Args: obj: The object to validate. strict: Whether to enforce types strictly. from_attributes: Whether to extract data from object attributes. context: Additional context to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Raises: ValidationError: If the object could not be validated. Returns: The validated model instance. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_python( obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name ) @classmethod def model_validate_json( cls, json_data: str \| bytes \| bytearray, *, strict: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """!!! abstract "Usage Documentation" [JSON Parsing](../concepts/json.md#json-parsing) Validate the given JSON data against the Pydantic model. Args: json_data: The JSON data to validate. strict: Whether to enforce types strictly. context: Extra variables to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Returns: The validated Pydantic model. Raises: ValidationError: If `json_data` is not a JSON string or the object could not be validated. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_json( json_data, strict=strict, context=context, by_alias=by_alias, by_name=by_name ) @classmethod def model_validate_strings( cls, obj: Any, *, strict: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """Validate the given object with string data against the Pydantic model. Args: obj: The object containing string data to validate. strict: Whether to enforce types strictly. context: Extra variables to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Returns: The validated Pydantic model. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_strings( obj, strict=strict, context=context, by_alias=by_alias, by_name=by_name ) @classmethod def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema: # This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass. # In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to # *not* be called if not overridden. warnings.warn( 'The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling ' '`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using ' '`handler(source)` instead. However, note that overriding this method on models can lead to unexpected ' 'side effects.', PydanticDeprecatedSince211, stacklevel=2, ) # Logic copied over from `GenerateSchema._model_schema`: schema = cls.__dict__.get('__pydantic_core_schema__') if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema): return cls.__pydantic_core_schema__ return handler(source) @classmethod def __get_pydantic_json_schema__( cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler, /, ) -> JsonSchemaValue: """Hook into generating the model's JSON schema. Args: core_schema: A `pydantic-core` CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`), or just call the handler with the original schema. handler: Call into Pydantic's internal JSON schema generation. This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema generation fails. Since this gets called by `BaseModel.model_json_schema` you can override the `schema_generator` argument to that function to change JSON schema generation globally for a type. Returns: A JSON schema, as a Python object. """ return handler(core_schema) @classmethod def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass` only after the class is actually fully initialized. In particular, attributes like `model_fields` will be present when this is called. This is necessary because `__init_subclass__` will always be called by `type.__new__`, and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that `type.__new__` was called in such a manner that the class would already be sufficiently initialized. This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely, any kwargs passed to the class definition that aren't used internally by pydantic. Args: **kwargs: Any keyword arguments passed to the class definition that aren't used internally by pydantic. """ pass def __class_getitem__( cls, typevar_values: type[Any] \| tuple[type[Any], ...] ) -> type[BaseModel] \| _forward_ref.PydanticRecursiveRef: cached = _generics.get_cached_generic_type_early(cls, typevar_values) if cached is not None: return cached if cls is BaseModel: raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel') if not hasattr(cls, '__parameters__'): raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic') if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__: raise TypeError(f'{cls} is not a generic class') if not isinstance(typevar_values, tuple): typevar_values = (typevar_values,) # For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`, # this gives us `{T: str, U: bool, V: int}`: typevars_map = _generics.map_generic_model_arguments(cls, typevar_values) # We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`): typevar_values = tuple(v for v in typevars_map.values()) if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: submodel = cls # if arguments are equal to parameters it's the same object _generics.set_cached_generic_type(cls, typevar_values, submodel) else: parent_args = cls.__pydantic_generic_metadata__['args'] if not parent_args: args = typevar_values else: args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) origin = cls.__pydantic_generic_metadata__['origin'] or cls model_name = origin.model_parametrized_name(args) params = tuple( {param: None for param in _generics.iter_contained_typevars(typevars_map.values())} ) # use dict as ordered set with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) if cached is not None: return cached if maybe_self_type is not None: return maybe_self_type # Attempt to rebuild the origin in case new types have been defined try: # depth 2 gets you above this __class_getitem__ call. # Note that we explicitly provide the parent ns, otherwise # `model_rebuild` will use the parent ns no matter if it is the ns of a module. # We don't want this here, as this has unexpected effects when a model # is being parametrized during a forward annotation evaluation. parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {} origin.model_rebuild(_types_namespace=parent_ns) except PydanticUndefinedAnnotation: # It's okay if it fails, it just means there are still undefined types # that could be evaluated later. pass submodel = _generics.create_generic_submodel(model_name, origin, args, params) # Cache the generated model *only* if not in the process of parametrizing # another model. In some valid scenarios, we miss the opportunity to cache # it but in some cases this results in `PydanticRecursiveRef` instances left # on `FieldInfo` annotations: if len(_generics.recursively_defined_type_refs()) == 1: _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) return submodel def __copy__(self) -> Self: """Returns a shallow copy of the model.""" cls = type(self) m = cls.__new__(cls) _object_setattr(m, '__dict__', copy(self.__dict__)) _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: _object_setattr(m, '__pydantic_private__', None) else: _object_setattr( m, '__pydantic_private__', {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, ) return m def __deepcopy__(self, memo: dict[int, Any] \| None = None) -> Self: """Returns a deep copy of the model.""" cls = type(self) m = cls.__new__(cls) _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str], # and attempting a deepcopy would be marginally slower. _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: _object_setattr(m, '__pydantic_private__', None) else: _object_setattr( m, '__pydantic_private__', deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo), ) return m if not TYPE_CHECKING: # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643 def __getattr__(self, item: str) -> Any: private_attributes = object.__getattribute__(self, '__private_attributes__') if item in private_attributes: attribute = private_attributes[item] if hasattr(attribute, '__get__'): return attribute.__get__(self, type(self)) # type: ignore try: # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items return self.__pydantic_private__[item] # type: ignore except KeyError as exc: raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc else: # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. # See `BaseModel.__repr_args__` for more details try: pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') except AttributeError: pydantic_extra = None if pydantic_extra: try: return pydantic_extra[item] except KeyError as exc: raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc else: if hasattr(self.__class__, item): return super().__getattribute__(item) # Raises AttributeError if appropriate else: # this is the current error raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') def __setattr__(self, name: str, value: Any) -> None: if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None: setattr_handler(self, name, value) # if None is returned from _setattr_handler, the attribute was set directly elif (setattr_handler := self._setattr_handler(name, value)) is not None: setattr_handler(self, name, value) # call here to not memo on possibly unknown fields self.__pydantic_setattr_handlers__[name] = setattr_handler # memoize the handler for faster access def _setattr_handler(self, name: str, value: Any) -> Callable[[BaseModel, str, Any], None] \| None: """Get a handler for setting an attribute on the model instance. Returns: A handler for setting an attribute on the model instance. Used for memoization of the handler. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__` Returns `None` when memoization is not safe, then the attribute is set directly. """ cls = self.__class__ if name in cls.__class_vars__: raise AttributeError( f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. ' f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.' ) elif not _fields.is_valid_field_name(name): if (attribute := cls.__private_attributes__.get(name)) is not None: if hasattr(attribute, '__set__'): return lambda model, _name, val: attribute.__set__(model, val) else: return _SIMPLE_SETATTR_HANDLERS['private'] else: _object_setattr(self, name, value) return None # Can not return memoized handler with possibly freeform attr names attr = getattr(cls, name, None) # NOTE: We currently special case properties and `cached_property`, but we might need # to generalize this to all data/non-data descriptors at some point. For non-data descriptors # (such as `cached_property`), it isn't obvious though. `cached_property` caches the value # to the instance's `__dict__`, but other non-data descriptors might do things differently. if isinstance(attr, cached_property): return _SIMPLE_SETATTR_HANDLERS['cached_property'] _check_frozen(cls, name, value) # We allow properties to be set only on non frozen models for now (to match dataclasses). # This can be changed if it ever gets requested. if isinstance(attr, property): return lambda model, _name, val: attr.__set__(model, val) elif cls.model_config.get('validate_assignment'): return _SIMPLE_SETATTR_HANDLERS['validate_assignment'] elif name not in cls.__pydantic_fields__: if cls.model_config.get('extra') != 'allow': # TODO - matching error raise ValueError(f'"{cls.__name__}" object has no field "{name}"') elif attr is None: # attribute does not exist, so put it in extra self.__pydantic_extra__[name] = value return None # Can not return memoized handler with possibly freeform attr names else: # attribute _does_ exist, and was not in extra, so update it return _SIMPLE_SETATTR_HANDLERS['extra_known'] else: return _SIMPLE_SETATTR_HANDLERS['model_field'] def __delattr__(self, item: str) -> Any: cls = self.__class__ if item in self.__private_attributes__: attribute = self.__private_attributes__[item] if hasattr(attribute, '__delete__'): attribute.__delete__(self) # type: ignore return try: # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items del self.__pydantic_private__[item] # type: ignore return except KeyError as exc: raise AttributeError(f'{cls.__name__!r} object has no attribute {item!r}') from exc # Allow cached properties to be deleted (even if the class is frozen): attr = getattr(cls, item, None) if isinstance(attr, cached_property): return object.__delattr__(self, item) _check_frozen(cls, name=item, value=None) if item in self.__pydantic_fields__: object.__delattr__(self, item) elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: del self.__pydantic_extra__[item] else: try: object.__delattr__(self, item) except AttributeError: raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block: def __replace__(self, **changes: Any) -> Self: return self.model_copy(update=changes) def __getstate__(self) -> dict[Any, Any]: private = self.__pydantic_private__ if private: private = {k: v for k, v in private.items() if v is not PydanticUndefined} return { '__dict__': self.__dict__, '__pydantic_extra__': self.__pydantic_extra__, '__pydantic_fields_set__': self.__pydantic_fields_set__, '__pydantic_private__': private, } def __setstate__(self, state: dict[Any, Any]) -> None: _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) _object_setattr(self, '__dict__', state.get('__dict__', {})) if not TYPE_CHECKING: def __eq__(self, other: Any) -> bool: if isinstance(other, BaseModel): # When comparing instances of generic types for equality, as long as all field values are equal, # only require their generic origin types to be equal, rather than exact type equality. # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1). self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ # Perform common checks first if not ( self_type == other_type and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None) and self.__pydantic_extra__ == other.__pydantic_extra__ ): return False # We only want to compare pydantic fields but ignoring fields is costly. # We'll perform a fast check first, and fallback only when needed # See GH-7444 and GH-7825 for rationale and a performance benchmark # First, do the fast (and sometimes faulty) __dict__ comparison if self.__dict__ == other.__dict__: # If the check above passes, then pydantic fields are equal, we can return early return True # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return # early if there are no keys to ignore (we would just return False later on anyway) model_fields = type(self).__pydantic_fields__.keys() if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: return False # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore # Resort to costly filtering of the __dict__ objects # We use operator.itemgetter because it is much faster than dict comprehensions # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute # raises an error in BaseModel.__getattr__ instead of returning the class attribute # So we can use operator.itemgetter() instead of operator.attrgetter() getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL try: return getter(self.__dict__) == getter(other.__dict__) except KeyError: # In rare cases (such as when using the deprecated BaseModel.copy() method), # the __dict__ may not contain all model fields, which is how we can get here. # getter(self.__dict__) is much faster than any 'safe' method that accounts # for missing keys, and wrapping it in a `try` doesn't slow things down much # in the common case. self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__) other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__) return getter(self_fields_proxy) == getter(other_fields_proxy) # other instance is not a BaseModel else: return NotImplemented # delegate to the other item in the comparison if TYPE_CHECKING: # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of # subclass initialization. def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]): """This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs. ```python from pydantic import BaseModel class MyModel(BaseModel, extra='allow'): ... ``` However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.) Args: **kwargs: Keyword arguments passed to the class definition, which set model_config Note: You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called *after* the class is fully initialized. """ def __iter__(self) -> TupleGenerator: """So `dict(model)` works.""" yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')] extra = self.__pydantic_extra__ if extra: yield from extra.items() def __repr__(self) -> str: return f'{self.__repr_name__()}({self.__repr_str__(", ")})' def __repr_args__(self) -> _repr.ReprArgs: # Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such # modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__` # below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration. computed_fields_repr_args = [ (k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr ] for k, v in self.__dict__.items(): field = self.__pydantic_fields__.get(k) if field and field.repr: if v is not self: yield k, v else: yield k, self.__repr_recursion__(v) # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. # This can happen if a `ValidationError` is raised during initialization and the instance's # repr is generated as part of the exception handling. Therefore, we use `getattr` here # with a fallback, even though the type hints indicate the attribute will always be present. try: pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') except AttributeError: pydantic_extra = None if pydantic_extra is not None: yield from ((k, v) for k, v in pydantic_extra.items()) yield from computed_fields_repr_args # take logic from `_repr.Representation` without the side effects of inheritance, see #5740 __repr_name__ = _repr.Representation.__repr_name__ __repr_recursion__ = _repr.Representation.__repr_recursion__ __repr_str__ = _repr.Representation.__repr_str__ __pretty__ = _repr.Representation.__pretty__ __rich_repr__ = _repr.Representation.__rich_repr__ def __str__(self) -> str: return self.__repr_str__(' ') # ##### Deprecated methods from v1 ##### @property @typing_extensions.deprecated( 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None ) def __fields__(self) -> dict[str, FieldInfo]: warnings.warn( 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return getattr(type(self), '__pydantic_fields__', {}) @property @typing_extensions.deprecated( 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', category=None, ) def __fields_set__(self) -> set[str]: warnings.warn( 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return self.__pydantic_fields_set__ @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None) def dict( # noqa: D102 self, *, include: IncEx \| None = None, exclude: IncEx \| None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Dict[str, Any]: # noqa UP006 warnings.warn( 'The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return self.model_dump( include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None) def json( # noqa: D102 self, *, include: IncEx \| None = None, exclude: IncEx \| None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] \| None = PydanticUndefined, # type: ignore[assignment] models_as_dict: bool = PydanticUndefined, # type: ignore[assignment] **dumps_kwargs: Any, ) -> str: warnings.warn( 'The `json` method is deprecated; use `model_dump_json` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) if encoder is not PydanticUndefined: raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.') if models_as_dict is not PydanticUndefined: raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.') if dumps_kwargs: raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.') return self.model_dump_json( include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) @classmethod @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None) def parse_obj(cls, obj: Any) -> Self: # noqa: D102 warnings.warn( 'The `parse_obj` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return cls.model_validate(obj) @classmethod @typing_extensions.deprecated( 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 'otherwise load the data then use `model_validate` instead.', category=None, ) def parse_raw( # noqa: D102 cls, b: str \| bytes, *, content_type: str \| None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol \| None = None, allow_pickle: bool = False, ) -> Self: # pragma: no cover warnings.warn( 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' 'otherwise load the data then use `model_validate` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import parse try: obj = parse.load_str_bytes( b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, ) except (ValueError, TypeError) as exc: import json # try to match V1 if isinstance(exc, UnicodeDecodeError): type_str = 'value_error.unicodedecode' elif isinstance(exc, json.JSONDecodeError): type_str = 'value_error.jsondecode' elif isinstance(exc, ValueError): type_str = 'value_error' else: type_str = 'type_error' # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same error: pydantic_core.InitErrorDetails = { # The type: ignore on the next line is to ignore the requirement of LiteralString 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore 'loc': ('__root__',), 'input': b, } raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error]) return cls.model_validate(obj) @classmethod @typing_extensions.deprecated( 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' 'use `model_validate_json`, otherwise `model_validate` instead.', category=None, ) def parse_file( # noqa: D102 cls, path: str \| Path, *, content_type: str \| None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol \| None = None, allow_pickle: bool = False, ) -> Self: warnings.warn( 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' 'use `model_validate_json`, otherwise `model_validate` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import parse obj = parse.load_file( path, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, ) return cls.parse_obj(obj) @classmethod @typing_extensions.deprecated( 'The `from_orm` method is deprecated; set ' "`model_config['from_attributes']=True` and use `model_validate` instead.", category=None, ) def from_orm(cls, obj: Any) -> Self: # noqa: D102 warnings.warn( 'The `from_orm` method is deprecated; set ' "`model_config['from_attributes']=True` and use `model_validate` instead.", category=PydanticDeprecatedSince20, stacklevel=2, ) if not cls.model_config.get('from_attributes', None): raise PydanticUserError( 'You must set the config attribute `from_attributes=True` to use from_orm', code=None ) return cls.model_validate(obj) @classmethod @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None) def construct(cls, _fields_set: set[str] \| None = None, **values: Any) -> Self: # noqa: D102 warnings.warn( 'The `construct` method is deprecated; use `model_construct` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return cls.model_construct(_fields_set=_fields_set, **values) @typing_extensions.deprecated( 'The `copy` method is deprecated; use `model_copy` instead. ' 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', category=None, ) def copy( self, *, include: AbstractSetIntStr \| MappingIntStrAny \| None = None, exclude: AbstractSetIntStr \| MappingIntStrAny \| None = None, update: Dict[str, Any] \| None = None, # noqa UP006 deep: bool = False, ) -> Self: # pragma: no cover """Returns a copy of the model. !!! warning "Deprecated" This method is now deprecated; use `model_copy` instead. If you need `include` or `exclude`, use: ```python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) ``` Args: include: Optional set or mapping specifying which fields to include in the copied model. exclude: Optional set or mapping specifying which fields to exclude in the copied model. update: Optional dictionary of field-value pairs to override field values in the copied model. deep: If True, the values of fields that are Pydantic models will be deep-copied. Returns: A copy of the model with included, excluded and updated fields as specified. """ warnings.warn( 'The `copy` method is deprecated; use `model_copy` instead. ' 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import copy_internals values = dict( copy_internals._iter( self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False ), **(update or {}), ) if self.__pydantic_private__ is None: private = None else: private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined} if self.__pydantic_extra__ is None: extra: dict[str, Any] \| None = None else: extra = self.__pydantic_extra__.copy() for k in list(self.__pydantic_extra__): if k not in values: # k was in the exclude extra.pop(k) for k in list(values): if k in self.__pydantic_extra__: # k must have come from extra extra[k] = values.pop(k) # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg if update: fields_set = self.__pydantic_fields_set__ \| update.keys() else: fields_set = set(self.__pydantic_fields_set__) # removing excluded fields from `__pydantic_fields_set__` if exclude: fields_set -= set(exclude) return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep) @classmethod @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None) def schema( # noqa: D102 cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE ) -> Dict[str, Any]: # noqa UP006 warnings.warn( 'The `schema` method is deprecated; use `model_json_schema` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template) @classmethod @typing_extensions.deprecated( 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', category=None, ) def schema_json( # noqa: D102 cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any ) -> str: # pragma: no cover warnings.warn( 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) import json from .deprecated.json import pydantic_encoder return json.dumps( cls.model_json_schema(by_alias=by_alias, ref_template=ref_template), default=pydantic_encoder, **dumps_kwargs, ) @classmethod @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None) def validate(cls, value: Any) -> Self: # noqa: D102 warnings.warn( 'The `validate` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) return cls.model_validate(value) @classmethod @typing_extensions.deprecated( 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', category=None, ) def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102 warnings.warn( 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', category=PydanticDeprecatedSince20, stacklevel=2, ) if localns: # pragma: no cover raise TypeError('`localns` arguments are not longer accepted.') cls.model_rebuild(force=True) @typing_extensions.deprecated( 'The private method `_iter` will be removed and should no longer be used.', category=None ) def _iter(self, *args: Any, **kwargs: Any) -> Any: warnings.warn( 'The private method `_iter` will be removed and should no longer be used.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import copy_internals return copy_internals._iter(self, *args, **kwargs) @typing_extensions.deprecated( 'The private method `_copy_and_set_values` will be removed and should no longer be used.', category=None, ) def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any: warnings.warn( 'The private method `_copy_and_set_values` will be removed and should no longer be used.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import copy_internals return copy_internals._copy_and_set_values(self, *args, **kwargs) @classmethod @typing_extensions.deprecated( 'The private method `_get_value` will be removed and should no longer be used.', category=None, ) def _get_value(cls, *args: Any, **kwargs: Any) -> Any: warnings.warn( 'The private method `_get_value` will be removed and should no longer be used.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import copy_internals return copy_internals._get_value(cls, *args, **kwargs) @typing_extensions.deprecated( 'The private method `_calculate_keys` will be removed and should no longer be used.', category=None, ) def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any: warnings.warn( 'The private method `_calculate_keys` will be removed and should no longer be used.', category=PydanticDeprecatedSince20, stacklevel=2, ) from .deprecated import copy_internals return copy_internals._calculate_keys(self, *args, **kwargs)`` | ### \_\_init\_\_ [¶](#pydantic.BaseModel.__init__ "Permanent link") `__init__(**data: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> None` Raises [`ValidationError`](../pydantic_core/#pydantic_core.ValidationError) if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name. Source code in `pydantic/main.py` | | | | --- | --- | | 243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260 | ``def __init__(self, /, **data: Any) -> None: """Create a new model by parsing and validating input data from keyword arguments. Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) if self is not validated_self: warnings.warn( 'A custom validator is returning a value other than `self`.\n' "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n" 'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.', stacklevel=2, )`` | ### model\_config `class-attribute` [¶](#pydantic.BaseModel.model_config "Permanent link") `model_config: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") = [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") ()` Configuration for the model, should be a dictionary conforming to [`ConfigDict`](../config/#pydantic.config.ConfigDict) . ### model\_fields `classmethod` [¶](#pydantic.BaseModel.model_fields "Permanent link") `model_fields() -> dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](../fields/#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ]` A mapping of field names to their respective [`FieldInfo`](../fields/#pydantic.fields.FieldInfo) instances. Warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. Source code in `pydantic/main.py` | | | | --- | --- | | 265
266
267
268
269
270
271
272
273
274 | ``@_utils.deprecated_instance_property @classmethod def model_fields(cls) -> dict[str, FieldInfo]: """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances. !!! warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. """ return getattr(cls, '__pydantic_fields__', {})`` | ### model\_computed\_fields `classmethod` [¶](#pydantic.BaseModel.model_computed_fields "Permanent link") `model_computed_fields() -> dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](../fields/#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ]` A mapping of computed field names to their respective [`ComputedFieldInfo`](../fields/#pydantic.fields.ComputedFieldInfo) instances. Warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. Source code in `pydantic/main.py` | | | | --- | --- | | 276
277
278
279
280
281
282
283
284
285 | ``@_utils.deprecated_instance_property @classmethod def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]: """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances. !!! warning Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class. """ return getattr(cls, '__pydantic_computed_fields__', {})`` | ### \_\_pydantic\_core\_schema\_\_ `class-attribute` [¶](#pydantic.BaseModel.__pydantic_core_schema__ "Permanent link") `__pydantic_core_schema__: CoreSchema` The core schema of the model. ### model\_extra `property` [¶](#pydantic.BaseModel.model_extra "Permanent link") `model_extra: dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None` Get extra fields set during validation. Returns: | Type | Description | | --- | --- | | `dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`. | ### model\_fields\_set `property` [¶](#pydantic.BaseModel.model_fields_set "Permanent link") `model_fields_set: [set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` Returns the set of fields that have been explicitly set on this model instance. Returns: | Type | Description | | --- | --- | | `[set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` | A set of strings representing the fields that have been set, i.e. that were not filled from defaults. | ### model\_construct `classmethod` [¶](#pydantic.BaseModel.model_construct "Permanent link") `model_construct( _fields_set: [set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = None, **values: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> Self` Creates a new instance of the `Model` class with validated data. Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. Default values are respected, but no other validation is performed. Note `model_construct()` generally respects the `model_config.extra` setting on the provided model. That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in an error if extra values are passed, but they will be ignored. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `_fields_set` | `[set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [`model_fields_set`](#pydantic.BaseModel.model_fields_set)
attribute. Otherwise, the field names from the `values` argument will be used. | `None` | | `values` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | Trusted or pre-validated data dictionary. | `{}` | Returns: | Type | Description | | --- | --- | | `Self` | A new instance of the `Model` class with validated data. | Source code in `pydantic/main.py` | | | | --- | --- | | 306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385 | ``@classmethod def model_construct(cls, _fields_set: set[str] \| None = None, **values: Any) -> Self: # noqa: C901 """Creates a new instance of the `Model` class with validated data. Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. Default values are respected, but no other validation is performed. !!! note `model_construct()` generally respects the `model_config.extra` setting on the provided model. That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in an error if extra values are passed, but they will be ignored. Args: _fields_set: A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the `values` argument will be used. values: Trusted or pre-validated data dictionary. Returns: A new instance of the `Model` class with validated data. """ m = cls.__new__(cls) fields_values: dict[str, Any] = {} fields_set = set() for name, field in cls.__pydantic_fields__.items(): if field.alias is not None and field.alias in values: fields_values[name] = values.pop(field.alias) fields_set.add(name) if (name not in fields_set) and (field.validation_alias is not None): validation_aliases: list[str \| AliasPath] = ( field.validation_alias.choices if isinstance(field.validation_alias, AliasChoices) else [field.validation_alias] ) for alias in validation_aliases: if isinstance(alias, str) and alias in values: fields_values[name] = values.pop(alias) fields_set.add(name) break elif isinstance(alias, AliasPath): value = alias.search_dict_for_path(values) if value is not PydanticUndefined: fields_values[name] = value fields_set.add(name) break if name not in fields_set: if name in values: fields_values[name] = values.pop(name) fields_set.add(name) elif not field.is_required(): fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values) if _fields_set is None: _fields_set = fields_set _extra: dict[str, Any] \| None = values if cls.model_config.get('extra') == 'allow' else None _object_setattr(m, '__dict__', fields_values) _object_setattr(m, '__pydantic_fields_set__', _fields_set) if not cls.__pydantic_root_model__: _object_setattr(m, '__pydantic_extra__', _extra) if cls.__pydantic_post_init__: m.model_post_init(None) # update private attributes with values set if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: for k, v in values.items(): if k in m.__private_attributes__: m.__pydantic_private__[k] = v elif not cls.__pydantic_root_model__: # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist # Since it doesn't, that means that `__pydantic_private__` should be set to None _object_setattr(m, '__pydantic_private__', None) return m`` | ### model\_copy [¶](#pydantic.BaseModel.model_copy "Permanent link") `model_copy( *, update: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "collections.abc.Mapping") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, deep: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> Self` Usage Documentation [`model_copy`](../../concepts/serialization/#model_copy) Returns a copy of the model. Note The underlying instance's [`__dict__`](https://docs.python.org/3/reference/datamodel.html#object.__dict__) attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties](https://docs.python.org/3/library/functools.html#functools.cached_property) ). Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `update` | `[Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "collections.abc.Mapping") [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data. | `None` | | `deep` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Set to `True` to make a deep copy of the model. | `False` | Returns: | Type | Description | | --- | --- | | `Self` | New model instance. | Source code in `pydantic/main.py` | | | | --- | --- | | 387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419 | ``def model_copy(self, *, update: Mapping[str, Any] \| None = None, deep: bool = False) -> Self: """!!! abstract "Usage Documentation" [`model_copy`](../concepts/serialization.md#model_copy) Returns a copy of the model. !!! note The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]). Args: update: Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data. deep: Set to `True` to make a deep copy of the model. Returns: New model instance. """ copied = self.__deepcopy__() if deep else self.__copy__() if update: if self.model_config.get('extra') == 'allow': for k, v in update.items(): if k in self.__pydantic_fields__: copied.__dict__[k] = v else: if copied.__pydantic_extra__ is None: copied.__pydantic_extra__ = {} copied.__pydantic_extra__[k] = v else: copied.__dict__.update(update) copied.__pydantic_fields_set__.update(update.keys()) return copied`` | ### model\_dump [¶](#pydantic.BaseModel.model_dump "Permanent link") `model_dump( *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["json", "python"] | [str](https://docs.python.org/3/library/stdtypes.html#str) = "python", include: IncEx | None = None, exclude: IncEx | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, exclude_unset: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_defaults: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, warnings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["none", "warn", "error"] ) = True, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Usage Documentation [`model_dump`](../../concepts/serialization/#modelmodel_dump) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['json', 'python'] \| [str](https://docs.python.org/3/library/stdtypes.html#str) ` | The mode in which `to_python` should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects. | `'python'` | | `include` | `IncEx \| None` | A set of fields to include in the output. | `None` | | `exclude` | `IncEx \| None` | A set of fields to exclude from the output. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | Additional context to pass to the serializer. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias in the dictionary key if defined. | `None` | | `exclude_unset` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have not been explicitly set. | `False` | | `exclude_defaults` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are set to their default value. | `False` | | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` | | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | If True, dumped values should be valid as input for non-idempotent types such as Json\[T\]. | `False` | | `warnings` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['none', 'warn', 'error']` | How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`](../pydantic_core/#pydantic_core.PydanticSerializationError)
. | `True` | | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`](../pydantic_core/#pydantic_core.PydanticSerializationError)
error is raised. | `None` | | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` | Returns: | Type | Description | | --- | --- | | `dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | A dictionary representation of the model. | Source code in `pydantic/main.py` | | | | --- | --- | | 421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477 | ``def model_dump( self, *, mode: Literal['json', 'python'] \| str = 'python', include: IncEx \| None = None, exclude: IncEx \| None = None, context: Any \| None = None, by_alias: bool \| None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool \| Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] \| None = None, serialize_as_any: bool = False, ) -> dict[str, Any]: """!!! abstract "Usage Documentation" [`model_dump`](../concepts/serialization.md#modelmodel_dump) Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. Args: mode: The mode in which `to_python` should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects. include: A set of fields to include in the output. exclude: A set of fields to exclude from the output. context: Additional context to pass to the serializer. by_alias: Whether to use the field's alias in the dictionary key if defined. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of `None`. round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. fallback: A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. Returns: A dictionary representation of the model. """ return self.__pydantic_serializer__.to_python( self, mode=mode, by_alias=by_alias, include=include, exclude=exclude, context=context, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, round_trip=round_trip, warnings=warnings, fallback=fallback, serialize_as_any=serialize_as_any, )`` | ### model\_dump\_json [¶](#pydantic.BaseModel.model_dump_json "Permanent link") `model_dump_json( *, indent: [int](https://docs.python.org/3/library/functions.html#int) | None = None, include: IncEx | None = None, exclude: IncEx | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, exclude_unset: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_defaults: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, warnings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["none", "warn", "error"] ) = True, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Usage Documentation [`model_dump_json`](../../concepts/serialization/#modelmodel_dump_json) Generates a JSON representation of the model using Pydantic's `to_json` method. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `indent` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Indentation to use in the JSON output. If None is passed, the output will be compact. | `None` | | `include` | `IncEx \| None` | Field(s) to include in the JSON output. | `None` | | `exclude` | `IncEx \| None` | Field(s) to exclude from the JSON output. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | Additional context to pass to the serializer. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to serialize using field aliases. | `None` | | `exclude_unset` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have not been explicitly set. | `False` | | `exclude_defaults` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are set to their default value. | `False` | | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` | | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | If True, dumped values should be valid as input for non-idempotent types such as Json\[T\]. | `False` | | `warnings` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['none', 'warn', 'error']` | How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`](../pydantic_core/#pydantic_core.PydanticSerializationError)
. | `True` | | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`](../pydantic_core/#pydantic_core.PydanticSerializationError)
error is raised. | `None` | | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | A JSON string representation of the model. | Source code in `pydantic/main.py` | | | | --- | --- | | 479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533 | ``def model_dump_json( self, *, indent: int \| None = None, include: IncEx \| None = None, exclude: IncEx \| None = None, context: Any \| None = None, by_alias: bool \| None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool \| Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] \| None = None, serialize_as_any: bool = False, ) -> str: """!!! abstract "Usage Documentation" [`model_dump_json`](../concepts/serialization.md#modelmodel_dump_json) Generates a JSON representation of the model using Pydantic's `to_json` method. Args: indent: Indentation to use in the JSON output. If None is passed, the output will be compact. include: Field(s) to include in the JSON output. exclude: Field(s) to exclude from the JSON output. context: Additional context to pass to the serializer. by_alias: Whether to serialize using field aliases. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of `None`. round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. fallback: A function to call when an unknown value is encountered. If not provided, a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. Returns: A JSON string representation of the model. """ return self.__pydantic_serializer__.to_json( self, indent=indent, include=include, exclude=exclude, context=context, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, round_trip=round_trip, warnings=warnings, fallback=fallback, serialize_as_any=serialize_as_any, ).decode()`` | ### model\_json\_schema `classmethod` [¶](#pydantic.BaseModel.model_json_schema "Permanent link") `model_json_schema( by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) = True, ref_template: [str](https://docs.python.org/3/library/stdtypes.html#str) = [DEFAULT_REF_TEMPLATE](../json_schema/#pydantic.json_schema.DEFAULT_REF_TEMPLATE "pydantic.json_schema.DEFAULT_REF_TEMPLATE") , schema_generator: [type](https://docs.python.org/3/glossary.html#term-type) [ [GenerateJsonSchema](../json_schema/#pydantic.json_schema.GenerateJsonSchema "pydantic.json_schema.GenerateJsonSchema") ] = [GenerateJsonSchema](../json_schema/#pydantic.json_schema.GenerateJsonSchema "pydantic.json_schema.GenerateJsonSchema") , mode: [JsonSchemaMode](../json_schema/#pydantic.json_schema.JsonSchemaMode "pydantic.json_schema.JsonSchemaMode") = "validation", ) -> dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Generates a JSON schema for a model class. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to use attribute aliases or not. | `True` | | `ref_template` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The reference template. | `[DEFAULT_REF_TEMPLATE](../json_schema/#pydantic.json_schema.DEFAULT_REF_TEMPLATE "pydantic.json_schema.DEFAULT_REF_TEMPLATE") ` | | `schema_generator` | `[type](https://docs.python.org/3/glossary.html#term-type) [[GenerateJsonSchema](../json_schema/#pydantic.json_schema.GenerateJsonSchema "pydantic.json_schema.GenerateJsonSchema") ]` | To override the logic used to generate the JSON schema, as a subclass of `GenerateJsonSchema` with your desired modifications | `[GenerateJsonSchema](../json_schema/#pydantic.json_schema.GenerateJsonSchema "pydantic.json_schema.GenerateJsonSchema") ` | | `mode` | `[JsonSchemaMode](../json_schema/#pydantic.json_schema.JsonSchemaMode "pydantic.json_schema.JsonSchemaMode") ` | The mode in which to generate the schema. | `'validation'` | Returns: | Type | Description | | --- | --- | | `dict[[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | The JSON schema for the given model class. | Source code in `pydantic/main.py` | | | | --- | --- | | 535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557 | ``@classmethod def model_json_schema( cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, mode: JsonSchemaMode = 'validation', ) -> dict[str, Any]: """Generates a JSON schema for a model class. Args: by_alias: Whether to use attribute aliases or not. ref_template: The reference template. schema_generator: To override the logic used to generate the JSON schema, as a subclass of `GenerateJsonSchema` with your desired modifications mode: The mode in which to generate the schema. Returns: The JSON schema for the given model class. """ return model_json_schema( cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode )`` | ### model\_parametrized\_name `classmethod` [¶](#pydantic.BaseModel.model_parametrized_name "Permanent link") `model_parametrized_name( params: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ...] ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Compute the class name for parametrizations of generic classes. This method can be overridden to achieve a custom naming scheme for generic BaseModels. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `params` | `[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ...]` | Tuple of types of the class. Given a generic class `Model` with 2 type variables and a concrete model `Model[str, int]`, the value `(str, int)` would be passed to `params`. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | String representing the new class where `params` are passed to `cls` as type variables. | Raises: | Type | Description | | --- | --- | | `[TypeError](https://docs.python.org/3/library/exceptions.html#TypeError) ` | Raised when trying to generate concrete names for non-generic models. | Source code in `pydantic/main.py` | | | | --- | --- | | 559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584 | ``@classmethod def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str: """Compute the class name for parametrizations of generic classes. This method can be overridden to achieve a custom naming scheme for generic BaseModels. Args: params: Tuple of types of the class. Given a generic class `Model` with 2 type variables and a concrete model `Model[str, int]`, the value `(str, int)` would be passed to `params`. Returns: String representing the new class where `params` are passed to `cls` as type variables. Raises: TypeError: Raised when trying to generate concrete names for non-generic models. """ if not issubclass(cls, typing.Generic): raise TypeError('Concrete names should only be generated for generic models.') # Any strings received should represent forward references, so we handle them specially below. # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future, # we may be able to remove this special case. param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] params_component = ', '.join(param_names) return f'{cls.__name__}[{params_component}]'`` | ### model\_post\_init [¶](#pydantic.BaseModel.model_post_init "Permanent link") `model_post_init(context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> None` Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. Source code in `pydantic/main.py` | | | | --- | --- | | 586
587
588
589
590 | ``def model_post_init(self, context: Any, /) -> None: """Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. """ pass`` | ### model\_rebuild `classmethod` [¶](#pydantic.BaseModel.model_rebuild "Permanent link") `model_rebuild( *, force: [bool](https://docs.python.org/3/library/functions.html#bool) = False, raise_errors: [bool](https://docs.python.org/3/library/functions.html#bool) = True, _parent_namespace_depth: [int](https://docs.python.org/3/library/functions.html#int) = 2, _types_namespace: MappingNamespace | None = None ) -> [bool](https://docs.python.org/3/library/functions.html#bool) | None` Try to rebuild the pydantic-core schema for the model. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `force` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to force the rebuilding of the model schema, defaults to `False`. | `False` | | `raise_errors` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to raise errors, defaults to `True`. | `True` | | `_parent_namespace_depth` | `[int](https://docs.python.org/3/library/functions.html#int) ` | The depth level of the parent namespace, defaults to 2. | `2` | | `_types_namespace` | `MappingNamespace \| None` | The types namespace, defaults to `None`. | `None` | Returns: | Type | Description | | --- | --- | | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Returns `None` if the schema is already "complete" and rebuilding was not required. | | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. | Source code in `pydantic/main.py` | | | | --- | --- | | 592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665 | ``@classmethod def model_rebuild( cls, *, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace \| None = None, ) -> bool \| None: """Try to rebuild the pydantic-core schema for the model. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. Args: force: Whether to force the rebuilding of the model schema, defaults to `False`. raise_errors: Whether to raise errors, defaults to `True`. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. _types_namespace: The types namespace, defaults to `None`. Returns: Returns `None` if the schema is already "complete" and rebuilding was not required. If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. """ if not force and cls.__pydantic_complete__: return None for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): if attr in cls.__dict__: # Deleting the validator/serializer is necessary as otherwise they can get reused in # pydantic-core. Same applies for the core schema that can be reused in schema generation. delattr(cls, attr) cls.__pydantic_complete__ = False if _types_namespace is not None: rebuild_ns = _types_namespace elif _parent_namespace_depth > 0: rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} else: rebuild_ns = {} parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} ns_resolver = _namespace_utils.NsResolver( parent_namespace={**rebuild_ns, **parent_ns}, ) if not cls.__pydantic_fields_complete__: typevars_map = _generics.get_model_typevars_map(cls) try: cls.__pydantic_fields__ = _fields.rebuild_model_fields( cls, ns_resolver=ns_resolver, typevars_map=typevars_map, ) except NameError as e: exc = PydanticUndefinedAnnotation.from_name_error(e) _mock_val_ser.set_model_mocks(cls, f'`{exc.name}`') if raise_errors: raise exc from e if not raise_errors and not cls.__pydantic_fields_complete__: # No need to continue with schema gen, it is guaranteed to fail return False assert cls.__pydantic_fields_complete__ return _model_construction.complete_model_class( cls, _config.ConfigWrapper(cls.model_config, check=False), raise_errors=raise_errors, ns_resolver=ns_resolver, )`` | ### model\_validate `classmethod` [¶](#pydantic.BaseModel.model_validate "Permanent link") `model_validate( obj: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, from_attributes: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> Self` Validate a pydantic model instance. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `obj` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The object to validate. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to enforce types strictly. | `None` | | `from_attributes` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to extract data from object attributes. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | Additional context to pass to the validator. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](../pydantic_core/#pydantic_core.ValidationError "pydantic_core.ValidationError") ` | If the object could not be validated. | Returns: | Type | Description | | --- | --- | | `Self` | The validated model instance. | Source code in `pydantic/main.py` | | | | --- | --- | | 667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705 | ``@classmethod def model_validate( cls, obj: Any, *, strict: bool \| None = None, from_attributes: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """Validate a pydantic model instance. Args: obj: The object to validate. strict: Whether to enforce types strictly. from_attributes: Whether to extract data from object attributes. context: Additional context to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Raises: ValidationError: If the object could not be validated. Returns: The validated model instance. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_python( obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name )`` | ### model\_validate\_json `classmethod` [¶](#pydantic.BaseModel.model_validate_json "Permanent link") `model_validate_json( json_data: [str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> Self` Usage Documentation [JSON Parsing](../../concepts/json/#json-parsing) Validate the given JSON data against the Pydantic model. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `json_data` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) \| [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) ` | The JSON data to validate. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to enforce types strictly. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | Extra variables to pass to the validator. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Returns: | Type | Description | | --- | --- | | `Self` | The validated Pydantic model. | Raises: | Type | Description | | --- | --- | | `[ValidationError](../pydantic_core/#pydantic_core.ValidationError "pydantic_core.ValidationError") ` | If `json_data` is not a JSON string or the object could not be validated. | Source code in `pydantic/main.py` | | | | --- | --- | | 707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746 | ``@classmethod def model_validate_json( cls, json_data: str \| bytes \| bytearray, *, strict: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """!!! abstract "Usage Documentation" [JSON Parsing](../concepts/json.md#json-parsing) Validate the given JSON data against the Pydantic model. Args: json_data: The JSON data to validate. strict: Whether to enforce types strictly. context: Extra variables to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Returns: The validated Pydantic model. Raises: ValidationError: If `json_data` is not a JSON string or the object could not be validated. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_json( json_data, strict=strict, context=context, by_alias=by_alias, by_name=by_name )`` | ### model\_validate\_strings `classmethod` [¶](#pydantic.BaseModel.model_validate_strings "Permanent link") `model_validate_strings( obj: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> Self` Validate the given object with string data against the Pydantic model. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `obj` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The object containing string data to validate. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to enforce types strictly. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | Extra variables to pass to the validator. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Returns: | Type | Description | | --- | --- | | `Self` | The validated Pydantic model. | Source code in `pydantic/main.py` | | | | --- | --- | | 748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781 | ``@classmethod def model_validate_strings( cls, obj: Any, *, strict: bool \| None = None, context: Any \| None = None, by_alias: bool \| None = None, by_name: bool \| None = None, ) -> Self: """Validate the given object with string data against the Pydantic model. Args: obj: The object containing string data to validate. strict: Whether to enforce types strictly. context: Extra variables to pass to the validator. by_alias: Whether to use the field's alias when validating against the provided input data. by_name: Whether to use the field's name when validating against the provided input data. Returns: The validated Pydantic model. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True if by_alias is False and by_name is not True: raise PydanticUserError( 'At least one of `by_alias` or `by_name` must be set to True.', code='validate-by-alias-and-name-false', ) return cls.__pydantic_validator__.validate_strings( obj, strict=strict, context=context, by_alias=by_alias, by_name=by_name )`` | pydantic.create\_model [¶](#pydantic.create_model "Permanent link") -------------------------------------------------------------------- `create_model( model_name: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *, __config__: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | None = None, __doc__: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, __base__: None = None, __module__: [str](https://docs.python.org/3/library/stdtypes.html#str) = __name__, __validators__: ( [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]] | None ) = None, __cls_kwargs__: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, **field_definitions: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ) -> [type](https://docs.python.org/3/glossary.html#term-type) [[BaseModel](#pydantic.BaseModel "pydantic.main.BaseModel") ]` `create_model( model_name: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *, __config__: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | None = None, __doc__: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, __base__: [type](https://docs.python.org/3/glossary.html#term-type) [ModelT] | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) [ModelT], ...], __module__: [str](https://docs.python.org/3/library/stdtypes.html#str) = __name__, __validators__: ( [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]] | None ) = None, __cls_kwargs__: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, **field_definitions: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ) -> [type](https://docs.python.org/3/glossary.html#term-type) [ModelT]` `create_model( model_name: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *, __config__: [ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") | None = None, __doc__: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, __base__: ( [type](https://docs.python.org/3/glossary.html#term-type) [ModelT] | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) [ModelT], ...] | None ) = None, __module__: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, __validators__: ( [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]] | None ) = None, __cls_kwargs__: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, **field_definitions: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], ) -> [type](https://docs.python.org/3/glossary.html#term-type) [ModelT]` Usage Documentation [Dynamic Model Creation](../../concepts/models/#dynamic-model-creation) Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a subclass of [`BaseModel`](#pydantic.BaseModel) . Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `model_name` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The name of the newly created model. | _required_ | | `__config__` | `[ConfigDict](../config/#pydantic.config.ConfigDict "pydantic.config.ConfigDict") \| None` | The configuration of the new model. | `None` | | `__doc__` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The docstring of the new model. | `None` | | `__base__` | `[type](https://docs.python.org/3/glossary.html#term-type) [ModelT] \| [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[type](https://docs.python.org/3/glossary.html#term-type) [ModelT], ...] \| None` | The base class or classes for the new model. | `None` | | `__module__` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The name of the module that the model belongs to; if `None`, the value is taken from `sys._getframe(1)` | `None` | | `__validators__` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [..., [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]] \| None` | A dictionary of methods that validate fields. The keys are the names of the validation methods to be added to the model, and the values are the validation methods themselves. You can read more about functional validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators)
. | `None` | | `__cls_kwargs__` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A dictionary of keyword arguments for class creation, such as `metaclass`. | `None` | | `**field_definitions` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | Field definitions of the new model. Either:

* a single element, representing the type annotation of the field.
* a two-tuple, the first element being the type and the second element the assigned value (either a default or the [`Field()`](../fields/#pydantic.fields.Field)
function). | `{}` | Returns: | Type | Description | | --- | --- | | `[type](https://docs.python.org/3/glossary.html#term-type) [ModelT]` | The new [model](#pydantic.BaseModel)
. | Raises: | Type | Description | | --- | --- | | `[PydanticUserError](../errors/#pydantic.errors.PydanticUserError "pydantic.errors.PydanticUserError") ` | If `__base__` and `__config__` are both passed. | Source code in `pydantic/main.py` | | | | --- | --- | | 1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779 | ``def create_model( # noqa: C901 model_name: str, /, *, __config__: ConfigDict \| None = None, __doc__: str \| None = None, __base__: type[ModelT] \| tuple[type[ModelT], ...] \| None = None, __module__: str \| None = None, __validators__: dict[str, Callable[..., Any]] \| None = None, __cls_kwargs__: dict[str, Any] \| None = None, # TODO PEP 747: replace `Any` by the TypeForm: **field_definitions: Any \| tuple[str, Any], ) -> type[ModelT]: """!!! abstract "Usage Documentation" [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation) Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a subclass of [`BaseModel`][pydantic.BaseModel]. Args: model_name: The name of the newly created model. __config__: The configuration of the new model. __doc__: The docstring of the new model. __base__: The base class or classes for the new model. __module__: The name of the module that the model belongs to; if `None`, the value is taken from `sys._getframe(1)` __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to be added to the model, and the values are the validation methods themselves. You can read more about functional validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators). __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`. **field_definitions: Field definitions of the new model. Either: - a single element, representing the type annotation of the field. - a two-tuple, the first element being the type and the second element the assigned value (either a default or the [`Field()`][pydantic.Field] function). Returns: The new [model][pydantic.BaseModel]. Raises: PydanticUserError: If `__base__` and `__config__` are both passed. """ if __base__ is not None: if __config__ is not None: raise PydanticUserError( 'to avoid confusion `__config__` and `__base__` cannot be used together', code='create-model-config-base', ) if not isinstance(__base__, tuple): __base__ = (__base__,) else: __base__ = (cast('type[ModelT]', BaseModel),) __cls_kwargs__ = __cls_kwargs__ or {} fields: dict[str, Any] = {} annotations: dict[str, Any] = {} for f_name, f_def in field_definitions.items(): if isinstance(f_def, tuple): if len(f_def) != 2: raise PydanticUserError( f'Field definition for {f_name!r} should a single element representing the type or a two-tuple, the first element ' 'being the type and the second element the assigned value (either a default or the `Field()` function).', code='create-model-field-definitions', ) annotations[f_name] = f_def[0] fields[f_name] = f_def[1] else: annotations[f_name] = f_def if __module__ is None: f = sys._getframe(1) __module__ = f.f_globals['__name__'] namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} if __doc__: namespace.update({'__doc__': __doc__}) if __validators__: namespace.update(__validators__) namespace.update(fields) if __config__: namespace['model_config'] = _config.ConfigWrapper(__config__).config_dict resolved_bases = types.resolve_bases(__base__) meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) if resolved_bases is not __base__: ns['__orig_bases__'] = __base__ namespace.update(ns) return meta( model_name, resolved_bases, namespace, __pydantic_reset_parent_namespace__=False, _create_model_module=__module__, **kwds, )`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Network Types - Pydantic Network Types ============= The networks module contains types for common network-related fields. MAX\_EMAIL\_LENGTH `module-attribute` [¶](#pydantic.networks.MAX_EMAIL_LENGTH "Permanent link") ------------------------------------------------------------------------------------------------ `MAX_EMAIL_LENGTH = 2048` Maximum length for an email. A somewhat arbitrary but very generous number compared to what is allowed by most implementations. UrlConstraints `dataclass` [¶](#pydantic.networks.UrlConstraints "Permanent link") ----------------------------------------------------------------------------------- `UrlConstraints( max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = None, allowed_schemes: [list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = None, host_required: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, default_host: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, default_port: [int](https://docs.python.org/3/library/functions.html#int) | None = None, default_path: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, )` Url constraints. Attributes: | Name | Type | Description | | --- | --- | --- | | `max_length` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | The maximum length of the url. Defaults to `None`. | | `allowed_schemes` | `[list](https://docs.python.org/3/glossary.html#term-list) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | The allowed schemes. Defaults to `None`. | | `host_required` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the host is required. Defaults to `None`. | | `default_host` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The default host. Defaults to `None`. | | `default_port` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | The default port. Defaults to `None`. | | `default_path` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The default path. Defaults to `None`. | ### defined\_constraints `property` [¶](#pydantic.networks.UrlConstraints.defined_constraints "Permanent link") `defined_constraints: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Fetch a key / value mapping of constraints to values that are not None. Used for core schema updates. AnyUrl [¶](#pydantic.networks.AnyUrl "Permanent link") ------------------------------------------------------- `AnyUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `_BaseUrl` Base type for all URLs. * Any scheme allowed * Top-level domain (TLD) not required * Host not required Assuming an input URL of `http://samuel:[[email protected]](/cdn-cgi/l/email-protection) :8000/the/path/?query=here#fragment=is;this=bit`, the types export the following properties: * `scheme`: the URL scheme (`http`), always set. * `host`: the URL host (`example.com`). * `username`: optional username if included (`samuel`). * `password`: optional password if included (`pass`). * `port`: optional port (`8000`). * `path`: optional path (`/the/path/`). * `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`). * `fragment`: optional fragment (`fragment=is;this=bit`). Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | AnyHttpUrl [¶](#pydantic.networks.AnyHttpUrl "Permanent link") --------------------------------------------------------------- `AnyHttpUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any http or https URL. * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | HttpUrl [¶](#pydantic.networks.HttpUrl "Permanent link") --------------------------------------------------------- `HttpUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any http or https URL. * TLD not required * Host not required * Max length 2083 `from pydantic import BaseModel, HttpUrl, ValidationError class MyModel(BaseModel): url: HttpUrl m = MyModel(url='http://www.example.com') # (1)! print(m.url) #> http://www.example.com/ try: MyModel(url='ftp://invalid.url') except ValidationError as e: print(e) ''' 1 validation error for MyModel url URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str] ''' try: MyModel(url='not a url') except ValidationError as e: print(e) ''' 1 validation error for MyModel url Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str] '''` 1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway. "International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via [punycode](https://en.wikipedia.org/wiki/Punycode) (see [this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important): `from pydantic import BaseModel, HttpUrl class MyModel(BaseModel): url: HttpUrl m1 = MyModel(url='http://puny£code.com') print(m1.url) #> http://xn--punycode-eja.com/ m2 = MyModel(url='https://www.аррӏе.com/') print(m2.url) #> https://www.xn--80ak6aa92e.com/ m3 = MyModel(url='https://www.example.珠宝/') print(m3.url) #> https://www.example.xn--pbt977c/` Underscores in Hostnames In Pydantic, underscores are allowed in all parts of a domain except the TLD. Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can. To explain this; consider the following two cases: * `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore. * `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain. Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore underscores are allowed, but you can always do further validation in a validator if desired. Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good (or at least big) company. Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | AnyWebsocketUrl [¶](#pydantic.networks.AnyWebsocketUrl "Permanent link") ------------------------------------------------------------------------- `AnyWebsocketUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any ws or wss URL. * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | WebsocketUrl [¶](#pydantic.networks.WebsocketUrl "Permanent link") ------------------------------------------------------------------- `WebsocketUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any ws or wss URL. * TLD not required * Host not required * Max length 2083 Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | FileUrl [¶](#pydantic.networks.FileUrl "Permanent link") --------------------------------------------------------- `FileUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any file URL. * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | FtpUrl [¶](#pydantic.networks.FtpUrl "Permanent link") ------------------------------------------------------- `FtpUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept ftp URL. * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | PostgresDsn [¶](#pydantic.networks.PostgresDsn "Permanent link") ----------------------------------------------------------------- `PostgresDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [MultiHostUrl](../pydantic_core/#pydantic_core.MultiHostUrl "pydantic_core.MultiHostUrl") | _BaseMultiHostUrl)` Bases: `_BaseMultiHostUrl` A type that will accept any Postgres DSN. * User info required * TLD not required * Host required * Supports multiple hosts If further validation is required, these properties can be used by validators to enforce specific behaviour: `from pydantic import ( BaseModel, HttpUrl, PostgresDsn, ValidationError, field_validator, ) class MyModel(BaseModel): url: HttpUrl m = MyModel(url='http://www.example.com') # the repr() method for a url will display all properties of the url print(repr(m.url)) #> HttpUrl('http://www.example.com/') print(m.url.scheme) #> http print(m.url.host) #> www.example.com print(m.url.port) #> 80 class MyDatabaseModel(BaseModel): db: PostgresDsn @field_validator('db') def check_db_name(cls, v): assert v.path and len(v.path) > 1, 'database must be provided' return v m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar') print(m.db) #> postgres://user:pass@localhost:5432/foobar try: MyDatabaseModel(db='postgres://user:pass@localhost:5432') except ValidationError as e: print(e) ''' 1 validation error for MyDatabaseModel db Assertion failed, database must be provided assert (None) + where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str] '''` Source code in `pydantic/networks.py` | | | | --- | --- | | 347
348 | `def __init__(self, url: str \| _CoreMultiHostUrl \| _BaseMultiHostUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | ### host `property` [¶](#pydantic.networks.PostgresDsn.host "Permanent link") `host: [str](https://docs.python.org/3/library/stdtypes.html#str)` The required URL host. CockroachDsn [¶](#pydantic.networks.CockroachDsn "Permanent link") ------------------------------------------------------------------- `CockroachDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any Cockroach DSN. * User info required * TLD not required * Host required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | ### host `property` [¶](#pydantic.networks.CockroachDsn.host "Permanent link") `host: [str](https://docs.python.org/3/library/stdtypes.html#str)` The required URL host. AmqpDsn [¶](#pydantic.networks.AmqpDsn "Permanent link") --------------------------------------------------------- `AmqpDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any AMQP DSN. * User info required * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | RedisDsn [¶](#pydantic.networks.RedisDsn "Permanent link") ----------------------------------------------------------- `RedisDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any Redis DSN. * User info required * TLD not required * Host required (e.g., `rediss://:pass@localhost`) Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | ### host `property` [¶](#pydantic.networks.RedisDsn.host "Permanent link") `host: [str](https://docs.python.org/3/library/stdtypes.html#str)` The required URL host. MongoDsn [¶](#pydantic.networks.MongoDsn "Permanent link") ----------------------------------------------------------- `MongoDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [MultiHostUrl](../pydantic_core/#pydantic_core.MultiHostUrl "pydantic_core.MultiHostUrl") | _BaseMultiHostUrl)` Bases: `_BaseMultiHostUrl` A type that will accept any MongoDB DSN. * User info not required * Database name not required * Port not required * User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`). Source code in `pydantic/networks.py` | | | | --- | --- | | 347
348 | `def __init__(self, url: str \| _CoreMultiHostUrl \| _BaseMultiHostUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | KafkaDsn [¶](#pydantic.networks.KafkaDsn "Permanent link") ----------------------------------------------------------- `KafkaDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any Kafka DSN. * User info required * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | NatsDsn [¶](#pydantic.networks.NatsDsn "Permanent link") --------------------------------------------------------- `NatsDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [MultiHostUrl](../pydantic_core/#pydantic_core.MultiHostUrl "pydantic_core.MultiHostUrl") | _BaseMultiHostUrl)` Bases: `_BaseMultiHostUrl` A type that will accept any NATS DSN. NATS is a connective technology built for the ever increasingly hyper-connected world. It is a single technology that enables applications to securely communicate across any combination of cloud vendors, on-premise, edge, web and mobile, and devices. More: https://nats.io Source code in `pydantic/networks.py` | | | | --- | --- | | 347
348 | `def __init__(self, url: str \| _CoreMultiHostUrl \| _BaseMultiHostUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | MySQLDsn [¶](#pydantic.networks.MySQLDsn "Permanent link") ----------------------------------------------------------- `MySQLDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any MySQL DSN. * User info required * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | MariaDBDsn [¶](#pydantic.networks.MariaDBDsn "Permanent link") --------------------------------------------------------------- `MariaDBDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any MariaDB DSN. * User info required * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | ClickHouseDsn [¶](#pydantic.networks.ClickHouseDsn "Permanent link") --------------------------------------------------------------------- `ClickHouseDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any ClickHouse DSN. * User info required * TLD not required * Host not required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | SnowflakeDsn [¶](#pydantic.networks.SnowflakeDsn "Permanent link") ------------------------------------------------------------------- `SnowflakeDsn(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Url](../pydantic_core/#pydantic_core.Url "pydantic_core.Url") | _BaseUrl)` Bases: `[AnyUrl](#pydantic.networks.AnyUrl "pydantic.networks.AnyUrl") ` A type that will accept any Snowflake DSN. * User info required * TLD not required * Host required Source code in `pydantic/networks.py` | | | | --- | --- | | 127
128 | `def __init__(self, url: str \| _CoreUrl \| _BaseUrl) -> None: self._url = _build_type_adapter(self.__class__).validate_python(url)._url` | ### host `property` [¶](#pydantic.networks.SnowflakeDsn.host "Permanent link") `host: [str](https://docs.python.org/3/library/stdtypes.html#str)` The required URL host. EmailStr [¶](#pydantic.networks.EmailStr "Permanent link") ----------------------------------------------------------- Info To use this type, you need to install the optional [`email-validator`](https://github.com/JoshData/python-email-validator) package: `pip install email-validator` Validate email addresses. `from pydantic import BaseModel, EmailStr class Model(BaseModel): email: EmailStr print(Model(email='[[email protected]](/cdn-cgi/l/email-protection) ')) #> email='[[email protected]](/cdn-cgi/l/email-protection) '` NameEmail [¶](#pydantic.networks.NameEmail "Permanent link") ------------------------------------------------------------- `NameEmail(name: [str](https://docs.python.org/3/library/stdtypes.html#str) , email: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `Representation` Info To use this type, you need to install the optional [`email-validator`](https://github.com/JoshData/python-email-validator) package: `pip install email-validator` Validate a name and email address combination, as specified by [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4) . The `NameEmail` has two properties: `name` and `email`. In case the `name` is not provided, it's inferred from the email address. `from pydantic import BaseModel, NameEmail class User(BaseModel): email: NameEmail user = User(email='Fred Bloggs <[[email protected]](/cdn-cgi/l/email-protection) >') print(user.email) #> Fred Bloggs <[[email protected]](/cdn-cgi/l/email-protection) > print(user.email.name) #> Fred Bloggs user = User(email='[[email protected]](/cdn-cgi/l/email-protection) ') print(user.email) #> fred.bloggs <[[email protected]](/cdn-cgi/l/email-protection) > print(user.email.name) #> fred.bloggs` Source code in `pydantic/networks.py` | | | | --- | --- | | 1040
1041
1042 | `def __init__(self, name: str, email: str): self.name = name self.email = email` | IPvAnyAddress [¶](#pydantic.networks.IPvAnyAddress "Permanent link") --------------------------------------------------------------------- Validate an IPv4 or IPv6 address. `from pydantic import BaseModel from pydantic.networks import IPvAnyAddress class IpModel(BaseModel): ip: IPvAnyAddress print(IpModel(ip='127.0.0.1')) #> ip=IPv4Address('127.0.0.1') try: IpModel(ip='http://www.example.com') except ValueError as e: print(e.errors()) ''' [ { 'type': 'ip_any_address', 'loc': ('ip',), 'msg': 'value is not a valid IPv4 or IPv6 address', 'input': 'http://www.example.com', } ] '''` IPvAnyInterface [¶](#pydantic.networks.IPvAnyInterface "Permanent link") ------------------------------------------------------------------------- Validate an IPv4 or IPv6 interface. IPvAnyNetwork [¶](#pydantic.networks.IPvAnyNetwork "Permanent link") --------------------------------------------------------------------- Validate an IPv4 or IPv6 network. validate\_email [¶](#pydantic.networks.validate_email "Permanent link") ------------------------------------------------------------------------ `validate_email(value: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [str](https://docs.python.org/3/library/stdtypes.html#str) ]` Email address validation using [email-validator](https://pypi.org/project/email-validator/) . Returns: | Type | Description | | --- | --- | | `[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [str](https://docs.python.org/3/library/stdtypes.html#str) ]` | A tuple containing the local part of the email (or the name for "pretty" email addresses) and the normalized email. | Raises: | Type | Description | | --- | --- | | `[PydanticCustomError](../pydantic_core/#pydantic_core.PydanticCustomError "pydantic_core.PydanticCustomError") ` | If the email is invalid. | Note Note that: * Raw IP address (literal) domain parts are not allowed. * `"John Doe <[[email protected]](/cdn-cgi/l/email-protection) >"` style "pretty" email addresses are processed. * Spaces are striped from the beginning and end of addresses, but no error is raised. Source code in `pydantic/networks.py` | | | | --- | --- | | 1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309 | ``def validate_email(value: str) -> tuple[str, str]: """Email address validation using [email-validator](https://pypi.org/project/email-validator/). Returns: A tuple containing the local part of the email (or the name for "pretty" email addresses) and the normalized email. Raises: PydanticCustomError: If the email is invalid. Note: Note that: * Raw IP address (literal) domain parts are not allowed. * `"John Doe <[[email protected]](/cdn-cgi/l/email-protection) >"` style "pretty" email addresses are processed. * Spaces are striped from the beginning and end of addresses, but no error is raised. """ if email_validator is None: import_email_validator() if len(value) > MAX_EMAIL_LENGTH: raise PydanticCustomError( 'value_error', 'value is not a valid email address: {reason}', {'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'}, ) m = pretty_email_regex.fullmatch(value) name: str \| None = None if m: unquoted_name, quoted_name, value = m.groups() name = unquoted_name or quoted_name email = value.strip() try: parts = email_validator.validate_email(email, check_deliverability=False) except email_validator.EmailNotValidError as e: raise PydanticCustomError( 'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])} ) from e email = parts.normalized assert email is not None name = name or parts.local_part return name, email`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Fields - Pydantic Fields ====== Defining fields on models. Field [¶](#pydantic.fields.Field "Permanent link") --------------------------------------------------- `Field( default: ellipsis, *, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, validation_alias: ( [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None ) = _Unset, serialization_alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = _Unset, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = _Unset, exclude: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, discriminator: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") | None = _Unset, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = _Unset, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, validate_default: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = _Unset, init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, init_var: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, pattern: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = _Unset, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: [float](https://docs.python.org/3/library/functions.html#float) | None = _Unset, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, max_digits: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, decimal_places: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, min_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, union_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["smart", "left_to_right"] = _Unset, fail_fast: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, **extra: Unpack[_EmptyKwargs] ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` `Field( default: _T, *, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, validation_alias: ( [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None ) = _Unset, serialization_alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = _Unset, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = _Unset, exclude: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, discriminator: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") | None = _Unset, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = _Unset, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, validate_default: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = _Unset, init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, init_var: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, pattern: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = _Unset, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: [float](https://docs.python.org/3/library/functions.html#float) | None = _Unset, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, max_digits: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, decimal_places: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, min_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, union_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["smart", "left_to_right"] = _Unset, fail_fast: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, **extra: Unpack[_EmptyKwargs] ) -> _T` `Field( *, default_factory: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], _T] | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]], _T] ), alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, validation_alias: ( [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None ) = _Unset, serialization_alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = _Unset, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = _Unset, exclude: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, discriminator: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") | None = _Unset, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = _Unset, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, validate_default: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = _Unset, init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, init_var: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, pattern: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = _Unset, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: [float](https://docs.python.org/3/library/functions.html#float) | None = _Unset, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, max_digits: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, decimal_places: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, min_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, union_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["smart", "left_to_right"] = _Unset, fail_fast: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, **extra: Unpack[_EmptyKwargs] ) -> _T` `Field( *, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, validation_alias: ( [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None ) = _Unset, serialization_alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = _Unset, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = _Unset, exclude: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, discriminator: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") | None = _Unset, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = _Unset, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, validate_default: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = _Unset, init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, init_var: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, pattern: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = _Unset, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: [float](https://docs.python.org/3/library/functions.html#float) | None = _Unset, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, max_digits: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, decimal_places: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, min_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, union_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["smart", "left_to_right"] = _Unset, fail_fast: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, **extra: Unpack[_EmptyKwargs] ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` `Field( default: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, *, default_factory: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None ) = _Unset, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, validation_alias: ( [str](https://docs.python.org/3/library/stdtypes.html#str) | [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") | [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") | None ) = _Unset, serialization_alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = _Unset, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = _Unset, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = _Unset, exclude: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, discriminator: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") | None = _Unset, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = _Unset, frozen: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, validate_default: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = _Unset, init: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, init_var: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, kw_only: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, pattern: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = _Unset, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, coerce_numbers_to_str: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: [float](https://docs.python.org/3/library/functions.html#float) | None = _Unset, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, max_digits: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, decimal_places: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, min_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, max_length: [int](https://docs.python.org/3/library/functions.html#int) | None = _Unset, union_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["smart", "left_to_right"] = _Unset, fail_fast: [bool](https://docs.python.org/3/library/functions.html#bool) | None = _Unset, **extra: Unpack[_EmptyKwargs] ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Usage Documentation [Fields](../../concepts/fields/) Create a field for objects that can be configured. Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`. Note * Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `default` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | Default value if the field is not set. | `PydanticUndefined` | | `default_factory` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data. | `_Unset` | | `alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case. | `_Unset` | | `alias_priority` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Priority of the alias. This affects whether an alias generator is used. | `_Unset` | | `validation_alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") \| [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") \| None` | Like `alias`, but only affects validation, not serialization. | `_Unset` | | `serialization_alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Like `alias`, but only affects serialization, not validation. | `_Unset` | | `title` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Human-readable title. | `_Unset` | | `field_title_generator` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns title for it. | `_Unset` | | `description` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Human-readable description. | `_Unset` | | `examples` | `[list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Example values for this field. | `_Unset` | | `exclude` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to exclude the field from the model serialization. | `_Unset` | | `discriminator` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") \| None` | Field name or Discriminator for discriminating the type in a tagged union. | `_Unset` | | `deprecated` | `Deprecated \| [str](https://docs.python.org/3/library/stdtypes.html#str) \| [bool](https://docs.python.org/3/library/functions.html#bool) \| None` | A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. | `_Unset` | | `json_schema_extra` | `JsonDict \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] \| None` | A dict or callable to provide extra JSON schema properties. | `_Unset` | | `frozen` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. | `_Unset` | | `validate_default` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | If `True`, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated. | `_Unset` | | `repr` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | A boolean indicating whether to include the field in the `__repr__` output. | `_Unset` | | `init` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.) | `_Unset` | | `init_var` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.) | `_Unset` | | `kw_only` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.) | `_Unset` | | `coerce_numbers_to_str` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). | `_Unset` | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | If `True`, strict validation is applied to the field. See [Strict Mode](../../concepts/strict_mode/)
for details. | `_Unset` | | `gt` | `SupportsGt \| None` | Greater than. If set, value must be greater than this. Only applicable to numbers. | `_Unset` | | `ge` | `SupportsGe \| None` | Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. | `_Unset` | | `lt` | `SupportsLt \| None` | Less than. If set, value must be less than this. Only applicable to numbers. | `_Unset` | | `le` | `SupportsLe \| None` | Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. | `_Unset` | | `multiple_of` | `[float](https://docs.python.org/3/library/functions.html#float) \| None` | Value must be a multiple of this. Only applicable to numbers. | `_Unset` | | `min_length` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Minimum length for iterables. | `_Unset` | | `max_length` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Maximum length for iterables. | `_Unset` | | `pattern` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [Pattern](https://docs.python.org/3/library/typing.html#typing.Pattern "typing.Pattern") [[str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | Pattern for strings (a regular expression). | `_Unset` | | `allow_inf_nan` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`](https://docs.python.org/3/library/decimal.html#decimal.Decimal)
numbers. | `_Unset` | | `max_digits` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Maximum number of allow digits for strings. | `_Unset` | | `decimal_places` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | Maximum number of decimal places allowed for numbers. | `_Unset` | | `union_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['smart', 'left_to_right']` | The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`. See [Union Mode](../../concepts/unions/#union-modes)
for details. | `_Unset` | | `fail_fast` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | If `True`, validation will stop on the first error. If `False`, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset). | `_Unset` | | `extra` | `Unpack[_EmptyKwargs]` | (Deprecated) Extra fields that will be included in the JSON schema.

Warning

The `extra` kwargs is deprecated. Use `json_schema_extra` instead. | `{}` | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | A new [`FieldInfo`](#pydantic.fields.FieldInfo)
. The return annotation is `Any` so `Field` can be used on type-annotated fields without causing a type error. | Source code in `pydantic/fields.py` | | | | --- | --- | | 933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138 | ``def Field( # noqa: C901 default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] \| Callable[[dict[str, Any]], Any] \| None = _Unset, alias: str \| None = _Unset, alias_priority: int \| None = _Unset, validation_alias: str \| AliasPath \| AliasChoices \| None = _Unset, serialization_alias: str \| None = _Unset, title: str \| None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] \| None = _Unset, description: str \| None = _Unset, examples: list[Any] \| None = _Unset, exclude: bool \| None = _Unset, discriminator: str \| types.Discriminator \| None = _Unset, deprecated: Deprecated \| str \| bool \| None = _Unset, json_schema_extra: JsonDict \| Callable[[JsonDict], None] \| None = _Unset, frozen: bool \| None = _Unset, validate_default: bool \| None = _Unset, repr: bool = _Unset, init: bool \| None = _Unset, init_var: bool \| None = _Unset, kw_only: bool \| None = _Unset, pattern: str \| typing.Pattern[str] \| None = _Unset, strict: bool \| None = _Unset, coerce_numbers_to_str: bool \| None = _Unset, gt: annotated_types.SupportsGt \| None = _Unset, ge: annotated_types.SupportsGe \| None = _Unset, lt: annotated_types.SupportsLt \| None = _Unset, le: annotated_types.SupportsLe \| None = _Unset, multiple_of: float \| None = _Unset, allow_inf_nan: bool \| None = _Unset, max_digits: int \| None = _Unset, decimal_places: int \| None = _Unset, min_length: int \| None = _Unset, max_length: int \| None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool \| None = _Unset, **extra: Unpack[_EmptyKwargs], ) -> Any: """!!! abstract "Usage Documentation" [Fields](../concepts/fields.md) Create a field for objects that can be configured. Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`. Note: - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None` Args: default: Default value if the field is not set. default_factory: A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data. alias: The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case. alias_priority: Priority of the alias. This affects whether an alias generator is used. validation_alias: Like `alias`, but only affects validation, not serialization. serialization_alias: Like `alias`, but only affects serialization, not validation. title: Human-readable title. field_title_generator: A callable that takes a field name and returns title for it. description: Human-readable description. examples: Example values for this field. exclude: Whether to exclude the field from the model serialization. discriminator: Field name or Discriminator for discriminating the type in a tagged union. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. json_schema_extra: A dict or callable to provide extra JSON schema properties. frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. validate_default: If `True`, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated. repr: A boolean indicating whether to include the field in the `__repr__` output. init: Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.) init_var: Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.) kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.) coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). strict: If `True`, strict validation is applied to the field. See [Strict Mode](../concepts/strict_mode.md) for details. gt: Greater than. If set, value must be greater than this. Only applicable to numbers. ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. lt: Less than. If set, value must be less than this. Only applicable to numbers. le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. multiple_of: Value must be a multiple of this. Only applicable to numbers. min_length: Minimum length for iterables. max_length: Maximum length for iterables. pattern: Pattern for strings (a regular expression). allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers. max_digits: Maximum number of allow digits for strings. decimal_places: Maximum number of decimal places allowed for numbers. union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`. See [Union Mode](../concepts/unions.md#union-modes) for details. fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset). extra: (Deprecated) Extra fields that will be included in the JSON schema. !!! warning Deprecated The `extra` kwargs is deprecated. Use `json_schema_extra` instead. Returns: A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on type-annotated fields without causing a type error. """ # Check deprecated and removed params from V1. This logic should eventually be removed. const = extra.pop('const', None) # type: ignore if const is not None: raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs') min_items = extra.pop('min_items', None) # type: ignore if min_items is not None: warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning) if min_length in (None, _Unset): min_length = min_items # type: ignore max_items = extra.pop('max_items', None) # type: ignore if max_items is not None: warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning) if max_length in (None, _Unset): max_length = max_items # type: ignore unique_items = extra.pop('unique_items', None) # type: ignore if unique_items is not None: raise PydanticUserError( ( '`unique_items` is removed, use `Set` instead' '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)' ), code='removed-kwargs', ) allow_mutation = extra.pop('allow_mutation', None) # type: ignore if allow_mutation is not None: warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning) if allow_mutation is False: frozen = True regex = extra.pop('regex', None) # type: ignore if regex is not None: raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs') if extra: warn( 'Using extra keyword arguments on `Field` is deprecated and will be removed.' ' Use `json_schema_extra` instead.' f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})', DeprecationWarning, ) if not json_schema_extra or json_schema_extra is _Unset: json_schema_extra = extra # type: ignore if ( validation_alias and validation_alias is not _Unset and not isinstance(validation_alias, (str, AliasChoices, AliasPath)) ): raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') if serialization_alias in (_Unset, None) and isinstance(alias, str): serialization_alias = alias if validation_alias in (_Unset, None): validation_alias = alias include = extra.pop('include', None) # type: ignore if include is not None: warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning) return FieldInfo.from_field( default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, field_title_generator=field_title_generator, description=description, examples=examples, exclude=exclude, discriminator=discriminator, deprecated=deprecated, json_schema_extra=json_schema_extra, frozen=frozen, pattern=pattern, validate_default=validate_default, repr=repr, init=init, init_var=init_var, kw_only=kw_only, coerce_numbers_to_str=coerce_numbers_to_str, strict=strict, gt=gt, ge=ge, lt=lt, le=le, multiple_of=multiple_of, min_length=min_length, max_length=max_length, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, union_mode=union_mode, fail_fast=fail_fast, )`` | FieldInfo [¶](#pydantic.fields.FieldInfo "Permanent link") ----------------------------------------------------------- `FieldInfo(**kwargs: Unpack[_FieldInfoInputs])` Bases: `Representation` This class holds information about a field. `FieldInfo` is used for any field definition regardless of whether the [`Field()`](#pydantic.fields.Field) function is explicitly used. Warning You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing [`BaseModel`](../base_model/#pydantic.BaseModel) `.model_fields` internals. Attributes: | Name | Type | Description | | --- | --- | --- | | `annotation` | `[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | The type annotation of the field. | | `default` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The default value of the field. | | `default_factory` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data. | | `alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The alias name of the field. | | `alias_priority` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | The priority of the field's alias. | | `validation_alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [AliasPath](../aliases/#pydantic.aliases.AliasPath "pydantic.aliases.AliasPath") \| [AliasChoices](../aliases/#pydantic.aliases.AliasChoices "pydantic.aliases.AliasChoices") \| None` | The validation alias of the field. | | `serialization_alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The serialization alias of the field. | | `title` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The title of the field. | | `field_title_generator` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns title for it. | | `description` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The description of the field. | | `examples` | `[list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | List of examples of the field. | | `exclude` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to exclude the field from the model serialization. | | `discriminator` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [Discriminator](../types/#pydantic.types.Discriminator "pydantic.types.Discriminator") \| None` | Field name or Discriminator for discriminating the type in a tagged union. | | `deprecated` | `Deprecated \| [str](https://docs.python.org/3/library/stdtypes.html#str) \| [bool](https://docs.python.org/3/library/functions.html#bool) \| None` | A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. | | `json_schema_extra` | `JsonDict \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] \| None` | A dict or callable to provide extra JSON schema properties. | | `frozen` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field is frozen. | | `validate_default` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the default value of the field. | | `repr` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include the field in representation of the model. | | `init` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should be included in the constructor of the dataclass. | | `init_var` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should _only_ be included in the constructor of the dataclass, and not stored. | | `kw_only` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether the field should be a keyword-only argument in the constructor of the dataclass. | | `metadata` | `[list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | List of metadata constraints. | See the signature of `pydantic.fields.Field` for more details about the expected arguments. Source code in `pydantic/fields.py` | | | | --- | --- | | 209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260 | ``def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None: """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function or one of the constructor classmethods. See the signature of `pydantic.fields.Field` for more details about the expected arguments. """ self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset} kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore self.annotation = kwargs.get('annotation') default = kwargs.pop('default', PydanticUndefined) if default is Ellipsis: self.default = PydanticUndefined self._attributes_set.pop('default', None) else: self.default = default self.default_factory = kwargs.pop('default_factory', None) if self.default is not PydanticUndefined and self.default_factory is not None: raise TypeError('cannot specify both default and default_factory') self.alias = kwargs.pop('alias', None) self.validation_alias = kwargs.pop('validation_alias', None) self.serialization_alias = kwargs.pop('serialization_alias', None) alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None self.title = kwargs.pop('title', None) self.field_title_generator = kwargs.pop('field_title_generator', None) self.description = kwargs.pop('description', None) self.examples = kwargs.pop('examples', None) self.exclude = kwargs.pop('exclude', None) self.discriminator = kwargs.pop('discriminator', None) # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) self.repr = kwargs.pop('repr', True) self.json_schema_extra = kwargs.pop('json_schema_extra', None) self.validate_default = kwargs.pop('validate_default', None) self.frozen = kwargs.pop('frozen', None) # currently only used on dataclasses self.init = kwargs.pop('init', None) self.init_var = kwargs.pop('init_var', None) self.kw_only = kwargs.pop('kw_only', None) self.metadata = self._collect_metadata(kwargs) # type: ignore # Private attributes: self._qualifiers: set[Qualifier] = set() # Used to rebuild FieldInfo instances: self._complete = True self._original_annotation: Any = PydanticUndefined self._original_assignment: Any = PydanticUndefined`` | ### from\_field `staticmethod` [¶](#pydantic.fields.FieldInfo.from_field "Permanent link") `from_field( default: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs] ) -> [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo")` Create a new `FieldInfo` object with the `Field` function. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `default` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The default value for the field. Defaults to Undefined. | `PydanticUndefined` | | `**kwargs` | `Unpack[_FromFieldInfoInputs]` | Additional arguments dictionary. | `{}` | Raises: | Type | Description | | --- | --- | | `[TypeError](https://docs.python.org/3/library/exceptions.html#TypeError) ` | If 'annotation' is passed as a keyword argument. | Returns: | Type | Description | | --- | --- | | `[FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ` | A new FieldInfo object with the given parameters. | Example This is how you can create a field with default value like this: `import pydantic class MyModel(pydantic.BaseModel): foo: int = pydantic.Field(4)` Source code in `pydantic/fields.py` | | | | --- | --- | | 262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288 | ``@staticmethod def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: """Create a new `FieldInfo` object with the `Field` function. Args: default: The default value for the field. Defaults to Undefined. **kwargs: Additional arguments dictionary. Raises: TypeError: If 'annotation' is passed as a keyword argument. Returns: A new FieldInfo object with the given parameters. Example: This is how you can create a field with default value like this: ```python import pydantic class MyModel(pydantic.BaseModel): foo: int = pydantic.Field(4) ``` """ if 'annotation' in kwargs: raise TypeError('"annotation" is not permitted as a Field keyword argument') return FieldInfo(default=default, **kwargs)`` | ### from\_annotation `staticmethod` [¶](#pydantic.fields.FieldInfo.from_annotation "Permanent link") `from_annotation( annotation: [type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], *, _source: AnnotationSource = ANY ) -> [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo")` Creates a `FieldInfo` instance from a bare annotation. This function is used internally to create a `FieldInfo` from a bare annotation like this: `import pydantic class MyModel(pydantic.BaseModel): foo: int # <-- like this` We also account for the case where the annotation can be an instance of `Annotated` and where one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.: `from typing import Annotated import annotated_types import pydantic class MyModel(pydantic.BaseModel): foo: Annotated[int, annotated_types.Gt(42)] bar: Annotated[int, pydantic.Field(gt=42)]` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `annotation` | `[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | An annotation object. | _required_ | Returns: | Type | Description | | --- | --- | | `[FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ` | An instance of the field metadata. | Source code in `pydantic/fields.py` | | | | --- | --- | | 290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365 | ``@staticmethod def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo: """Creates a `FieldInfo` instance from a bare annotation. This function is used internally to create a `FieldInfo` from a bare annotation like this: ```python import pydantic class MyModel(pydantic.BaseModel): foo: int # <-- like this ``` We also account for the case where the annotation can be an instance of `Annotated` and where one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.: ```python from typing import Annotated import annotated_types import pydantic class MyModel(pydantic.BaseModel): foo: Annotated[int, annotated_types.Gt(42)] bar: Annotated[int, pydantic.Field(gt=42)] ``` Args: annotation: An annotation object. Returns: An instance of the field metadata. """ try: inspected_ann = inspect_annotation( annotation, annotation_source=_source, unpack_type_aliases='skip', ) except ForbiddenQualifier as e: raise PydanticForbiddenQualifier(e.qualifier, annotation) # TODO check for classvar and error? # No assigned value, this happens when using a bare `Final` qualifier (also for other # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any` # because we don't have any assigned value. type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type final = 'final' in inspected_ann.qualifiers metadata = inspected_ann.metadata if not metadata: # No metadata, e.g. `field: int`, or `field: Final[str]`: field_info = FieldInfo(annotation=type_expr, frozen=final or None) field_info._qualifiers = inspected_ann.qualifiers return field_info # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)]`: field_info_annotations = [a for a in metadata if isinstance(a, FieldInfo)] field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=type_expr) new_field_info = copy(field_info) new_field_info.annotation = type_expr new_field_info.frozen = final or field_info.frozen field_metadata: list[Any] = [] for a in metadata: if typing_objects.is_deprecated(a): new_field_info.deprecated = a.message elif not isinstance(a, FieldInfo): field_metadata.append(a) else: field_metadata.extend(a.metadata) new_field_info.metadata = field_metadata new_field_info._qualifiers = inspected_ann.qualifiers return new_field_info`` | ### from\_annotated\_attribute `staticmethod` [¶](#pydantic.fields.FieldInfo.from_annotated_attribute "Permanent link") `from_annotated_attribute( annotation: [type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], default: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, _source: AnnotationSource = ANY ) -> [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo")` Create `FieldInfo` from an annotation with a default value. This is used in cases like the following: `from typing import Annotated import annotated_types import pydantic class MyModel(pydantic.BaseModel): foo: int = 4 # <-- like this bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `annotation` | `[type](https://docs.python.org/3/glossary.html#term-type) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | The type annotation of the field. | _required_ | | `default` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The default value of the field. | _required_ | Returns: | Type | Description | | --- | --- | | `[FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ` | A field object with the passed values. | Source code in `pydantic/fields.py` | | | | --- | --- | | 367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468 | ``@staticmethod def from_annotated_attribute( annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY ) -> FieldInfo: """Create `FieldInfo` from an annotation with a default value. This is used in cases like the following: ```python from typing import Annotated import annotated_types import pydantic class MyModel(pydantic.BaseModel): foo: int = 4 # <-- like this bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this ``` Args: annotation: The type annotation of the field. default: The default value of the field. Returns: A field object with the passed values. """ if annotation is default: raise PydanticUserError( 'Error when building FieldInfo from annotated attribute. ' "Make sure you don't have any field name clashing with a type annotation.", code='unevaluable-type-annotation', ) try: inspected_ann = inspect_annotation( annotation, annotation_source=_source, unpack_type_aliases='skip', ) except ForbiddenQualifier as e: raise PydanticForbiddenQualifier(e.qualifier, annotation) # TODO check for classvar and error? # TODO infer from the default, this can be done in v3 once we treat final fields with # a default as proper fields and not class variables: type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type final = 'final' in inspected_ann.qualifiers metadata = inspected_ann.metadata if isinstance(default, FieldInfo): # e.g. `field: int = Field(...)` default.annotation = type_expr default.metadata += metadata merged_default = FieldInfo.merge_field_infos( *[x for x in metadata if isinstance(x, FieldInfo)], default, annotation=default.annotation, ) merged_default.frozen = final or merged_default.frozen merged_default._qualifiers = inspected_ann.qualifiers return merged_default if isinstance(default, dataclasses.Field): # `collect_dataclass_fields()` passes the dataclass Field as a default. pydantic_field = FieldInfo._from_dataclass_field(default) pydantic_field.annotation = type_expr pydantic_field.metadata += metadata pydantic_field = FieldInfo.merge_field_infos( *[x for x in metadata if isinstance(x, FieldInfo)], pydantic_field, annotation=pydantic_field.annotation, ) pydantic_field.frozen = final or pydantic_field.frozen pydantic_field.init_var = 'init_var' in inspected_ann.qualifiers pydantic_field.init = getattr(default, 'init', None) pydantic_field.kw_only = getattr(default, 'kw_only', None) pydantic_field._qualifiers = inspected_ann.qualifiers return pydantic_field if not metadata: # No metadata, e.g. `field: int = ...`, or `field: Final[str] = ...`: field_info = FieldInfo(annotation=type_expr, default=default, frozen=final or None) field_info._qualifiers = inspected_ann.qualifiers return field_info # With metadata, e.g. `field: Annotated[int, Field(...), Gt(1)] = ...`: field_infos = [a for a in metadata if isinstance(a, FieldInfo)] field_info = FieldInfo.merge_field_infos(*field_infos, annotation=type_expr, default=default) field_metadata: list[Any] = [] for a in metadata: if typing_objects.is_deprecated(a): field_info.deprecated = a.message elif not isinstance(a, FieldInfo): field_metadata.append(a) else: field_metadata.extend(a.metadata) field_info.metadata = field_metadata field_info._qualifiers = inspected_ann.qualifiers return field_info`` | ### merge\_field\_infos `staticmethod` [¶](#pydantic.fields.FieldInfo.merge_field_infos "Permanent link") `merge_field_infos( *field_infos: [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") , **overrides: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ) -> [FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo")` Merge `FieldInfo` instances keeping only explicitly set attributes. Later `FieldInfo` instances override earlier ones. Returns: | Name | Type | Description | | --- | --- | --- | | `FieldInfo` | `[FieldInfo](#pydantic.fields.FieldInfo "pydantic.fields.FieldInfo") ` | A merged FieldInfo instance. | Source code in `pydantic/fields.py` | | | | --- | --- | | 470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534 | ``@staticmethod def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: """Merge `FieldInfo` instances keeping only explicitly set attributes. Later `FieldInfo` instances override earlier ones. Returns: FieldInfo: A merged FieldInfo instance. """ if len(field_infos) == 1: # No merging necessary, but we still need to make a copy and apply the overrides field_info = copy(field_infos[0]) field_info._attributes_set.update(overrides) default_override = overrides.pop('default', PydanticUndefined) if default_override is Ellipsis: default_override = PydanticUndefined if default_override is not PydanticUndefined: field_info.default = default_override for k, v in overrides.items(): setattr(field_info, k, v) return field_info # type: ignore merged_field_info_kwargs: dict[str, Any] = {} metadata = {} for field_info in field_infos: attributes_set = field_info._attributes_set.copy() try: json_schema_extra = attributes_set.pop('json_schema_extra') existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra') if existing_json_schema_extra is None: merged_field_info_kwargs['json_schema_extra'] = json_schema_extra if isinstance(existing_json_schema_extra, dict): if isinstance(json_schema_extra, dict): merged_field_info_kwargs['json_schema_extra'] = { **existing_json_schema_extra, **json_schema_extra, } if callable(json_schema_extra): warn( 'Composing `dict` and `callable` type `json_schema_extra` is not supported.' 'The `callable` type is being ignored.' "If you'd like support for this behavior, please open an issue on pydantic.", PydanticJsonSchemaWarning, ) elif callable(json_schema_extra): # if ever there's a case of a callable, we'll just keep the last json schema extra spec merged_field_info_kwargs['json_schema_extra'] = json_schema_extra except KeyError: pass # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances merged_field_info_kwargs.update(attributes_set) for x in field_info.metadata: if not isinstance(x, FieldInfo): metadata[type(x)] = x merged_field_info_kwargs.update(overrides) field_info = FieldInfo(**merged_field_info_kwargs) field_info.metadata = list(metadata.values()) return field_info`` | ### deprecation\_message `property` [¶](#pydantic.fields.FieldInfo.deprecation_message "Permanent link") `deprecation_message: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The deprecation message to be emitted, or `None` if not set. ### default\_factory\_takes\_validated\_data `property` [¶](#pydantic.fields.FieldInfo.default_factory_takes_validated_data "Permanent link") `default_factory_takes_validated_data: [bool](https://docs.python.org/3/library/functions.html#bool) | None` Whether the provided default factory callable has a validated data parameter. Returns `None` if no default factory is set. ### get\_default [¶](#pydantic.fields.FieldInfo.get_default "Permanent link") `get_default( *, call_default_factory: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [True], validated_data: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` `get_default( *, call_default_factory: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = ... ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` `get_default( *, call_default_factory: [bool](https://docs.python.org/3/library/functions.html#bool) = False, validated_data: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Get the default value. We expose an option for whether to call the default\_factory (if present), as calling it may result in side effects that we want to avoid. However, there are times when it really should be called (namely, when instantiating a model via `model_construct`). Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `call_default_factory` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to call the default factory or not. | `False` | | `validated_data` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | The already validated data to be passed to the default factory. | `None` | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The default value, calling the default factory if requested or `None` if not set. | Source code in `pydantic/fields.py` | | | | --- | --- | | 617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645 | ``def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] \| None = None) -> Any: """Get the default value. We expose an option for whether to call the default_factory (if present), as calling it may result in side effects that we want to avoid. However, there are times when it really should be called (namely, when instantiating a model via `model_construct`). Args: call_default_factory: Whether to call the default factory or not. validated_data: The already validated data to be passed to the default factory. Returns: The default value, calling the default factory if requested or `None` if not set. """ if self.default_factory is None: return _utils.smart_deepcopy(self.default) elif call_default_factory: if self.default_factory_takes_validated_data: fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory) if validated_data is None: raise ValueError( "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'." ) return fac(validated_data) else: fac = cast('Callable[[], Any]', self.default_factory) return fac() else: return None`` | ### is\_required [¶](#pydantic.fields.FieldInfo.is_required "Permanent link") `is_required() -> [bool](https://docs.python.org/3/library/functions.html#bool)` Check if the field is required (i.e., does not have a default value or factory). Returns: | Type | Description | | --- | --- | | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | `True` if the field is required, `False` otherwise. | Source code in `pydantic/fields.py` | | | | --- | --- | | 647
648
649
650
651
652
653 | ``def is_required(self) -> bool: """Check if the field is required (i.e., does not have a default value or factory). Returns: `True` if the field is required, `False` otherwise. """ return self.default is PydanticUndefined and self.default_factory is None`` | ### rebuild\_annotation [¶](#pydantic.fields.FieldInfo.rebuild_annotation "Permanent link") `rebuild_annotation() -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Attempts to rebuild the original annotation for use in function signatures. If metadata is present, it adds it to the original annotation using `Annotated`. Otherwise, it returns the original annotation as-is. Note that because the metadata has been flattened, the original annotation may not be reconstructed exactly as originally provided, e.g. if the original type had unrecognized annotations, or was annotated with a call to `pydantic.Field`. Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The rebuilt annotation. | Source code in `pydantic/fields.py` | | | | --- | --- | | 655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672 | ``def rebuild_annotation(self) -> Any: """Attempts to rebuild the original annotation for use in function signatures. If metadata is present, it adds it to the original annotation using `Annotated`. Otherwise, it returns the original annotation as-is. Note that because the metadata has been flattened, the original annotation may not be reconstructed exactly as originally provided, e.g. if the original type had unrecognized annotations, or was annotated with a call to `pydantic.Field`. Returns: The rebuilt annotation. """ if not self.metadata: return self.annotation else: # Annotated arguments must be a tuple return Annotated[(self.annotation, *self.metadata)] # type: ignore`` | ### apply\_typevars\_map [¶](#pydantic.fields.FieldInfo.apply_typevars_map "Permanent link") `apply_typevars_map( typevars_map: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "collections.abc.Mapping") [[TypeVar](https://docs.python.org/3/library/typing.html#typing.TypeVar "typing.TypeVar") , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None, globalns: GlobalsNamespace | None = None, localns: MappingNamespace | None = None, ) -> None` Apply a `typevars_map` to the annotation. This method is used when analyzing parametrized generic types to replace typevars with their concrete types. This method applies the `typevars_map` to the annotation in place. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `typevars_map` | `[Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "collections.abc.Mapping") [[TypeVar](https://docs.python.org/3/library/typing.html#typing.TypeVar "typing.TypeVar") , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A dictionary mapping type variables to their concrete types. | _required_ | | `globalns` | `GlobalsNamespace \| None` | The globals namespace to use during type annotation evaluation. | `None` | | `localns` | `MappingNamespace \| None` | The locals namespace to use during type annotation evaluation. | `None` | See Also pydantic.\_internal.\_generics.replace\_types is used for replacing the typevars with their concrete types. Source code in `pydantic/fields.py` | | | | --- | --- | | 674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696 | ``def apply_typevars_map( self, typevars_map: Mapping[TypeVar, Any] \| None, globalns: GlobalsNamespace \| None = None, localns: MappingNamespace \| None = None, ) -> None: """Apply a `typevars_map` to the annotation. This method is used when analyzing parametrized generic types to replace typevars with their concrete types. This method applies the `typevars_map` to the annotation in place. Args: typevars_map: A dictionary mapping type variables to their concrete types. globalns: The globals namespace to use during type annotation evaluation. localns: The locals namespace to use during type annotation evaluation. See Also: pydantic._internal._generics.replace_types is used for replacing the typevars with their concrete types. """ annotation, _ = _typing_extra.try_eval_type(self.annotation, globalns, localns) self.annotation = _generics.replace_types(annotation, typevars_map)`` | PrivateAttr [¶](#pydantic.fields.PrivateAttr "Permanent link") --------------------------------------------------------------- `PrivateAttr( default: _T, *, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False ) -> _T` `PrivateAttr( *, default_factory: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], _T], init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False ) -> _T` `PrivateAttr(*, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` `PrivateAttr( default: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, *, default_factory: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, init: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False] = False ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Usage Documentation [Private Model Attributes](../../concepts/models/#private-model-attributes) Indicates that an attribute is intended for private use and not handled during normal validation/serialization. Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner. Private attributes are stored in `__private_attributes__` on the model. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `default` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The attribute's default value. Defaults to Undefined. | `PydanticUndefined` | | `default_factory` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Callable that will be called when a default value is needed for this attribute. If both `default` and `default_factory` are set, an error will be raised. | `None` | | `init` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [False]` | Whether the attribute should be included in the constructor of the dataclass. Always `False`. | `False` | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | An instance of [`ModelPrivateAttr`](#pydantic.fields.ModelPrivateAttr)
class. | Raises: | Type | Description | | --- | --- | | `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` | If both `default` and `default_factory` are set. | Source code in `pydantic/fields.py` | | | | --- | --- | | 1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262 | ``def PrivateAttr( default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] \| None = None, init: Literal[False] = False, ) -> Any: """!!! abstract "Usage Documentation" [Private Model Attributes](../concepts/models.md#private-model-attributes) Indicates that an attribute is intended for private use and not handled during normal validation/serialization. Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner. Private attributes are stored in `__private_attributes__` on the model. Args: default: The attribute's default value. Defaults to Undefined. default_factory: Callable that will be called when a default value is needed for this attribute. If both `default` and `default_factory` are set, an error will be raised. init: Whether the attribute should be included in the constructor of the dataclass. Always `False`. Returns: An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class. Raises: ValueError: If both `default` and `default_factory` are set. """ if default is not PydanticUndefined and default_factory is not None: raise TypeError('cannot specify both default and default_factory') return ModelPrivateAttr( default, default_factory=default_factory, )`` | ModelPrivateAttr [¶](#pydantic.fields.ModelPrivateAttr "Permanent link") ------------------------------------------------------------------------- `ModelPrivateAttr( default: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, *, default_factory: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None )` Bases: `Representation` A descriptor for private attributes in class models. Warning You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.) Attributes: | Name | Type | Description | | --- | --- | --- | | `default` | | The default value of the attribute if not provided. | | `default_factory` | | A callable function that generates the default value of the attribute if not provided. | Source code in `pydantic/fields.py` | | | | --- | --- | | 1160
1161
1162
1163
1164
1165
1166
1167 | `def __init__( self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] \| None = None ) -> None: if default is Ellipsis: self.default = PydanticUndefined else: self.default = default self.default_factory = default_factory` | ### get\_default [¶](#pydantic.fields.ModelPrivateAttr.get_default "Permanent link") `get_default() -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Retrieve the default value of the object. If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object. If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned. Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The default value of the object. | Source code in `pydantic/fields.py` | | | | --- | --- | | 1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200 | ``def get_default(self) -> Any: """Retrieve the default value of the object. If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object. If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned. Returns: The default value of the object. """ return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()`` | computed\_field [¶](#pydantic.fields.computed_field "Permanent link") ---------------------------------------------------------------------- `computed_field(func: PropertyT) -> PropertyT` `computed_field( *, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = None, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = None, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = None, repr: [bool](https://docs.python.org/3/library/functions.html#bool) = True, return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[PropertyT], PropertyT]` `computed_field( func: PropertyT | None = None, /, *, alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None = None, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ) = None, description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ) = None, repr: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, ) -> PropertyT | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[PropertyT], PropertyT]` Usage Documentation [The `computed_field` decorator](../../concepts/fields/#the-computed_field-decorator) Decorator to include `property` and `cached_property` when serializing models or dataclasses. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. `from pydantic import BaseModel, computed_field class Rectangle(BaseModel): width: int length: int @computed_field @property def area(self) -> int: return self.width * self.length print(Rectangle(width=3, length=2).model_dump()) #> {'width': 3, 'length': 2, 'area': 6}` If applied to functions not yet decorated with `@property` or `@cached_property`, the function is automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE, and confuse static type checkers, thus explicit use of `@property` is recommended. Mypy Warning Even with the `@property` or `@cached_property` applied to your function before `@computed_field`, mypy may throw a `Decorated property not supported` error. See [mypy issue #1362](https://github.com/python/mypy/issues/1362) , for more information. To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line. [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error. ``import random from pydantic import BaseModel, computed_field class Square(BaseModel): width: float @computed_field def area(self) -> float: # converted to a `property` by `computed_field` return round(self.width**2, 2) @area.setter def area(self, new_area: float) -> None: self.width = new_area**0.5 @computed_field(alias='the magic number', repr=False) def random_number(self) -> int: return random.randint(0, 1_000) square = Square(width=1.3) # `random_number` does not appear in representation print(repr(square)) #> Square(width=1.3, area=1.69) print(square.random_number) #> 3 square.area = 4 print(square.model_dump_json(by_alias=True)) #> {"width":2.0,"area":4.0,"the magic number":3}`` Overriding with `computed_field` You can't override a field from a parent class with a `computed_field` in the child class. `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either. See the example below: `from pydantic import BaseModel, computed_field class Parent(BaseModel): a: str try: class Child(Parent): @computed_field @property def a(self) -> str: return 'new a' except TypeError as e: print(e) ''' Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible. '''` Private properties decorated with `@computed_field` have `repr=False` by default. `from functools import cached_property from pydantic import BaseModel, computed_field class Model(BaseModel): foo: int @computed_field @cached_property def _private_cached_property(self) -> int: return -self.foo @computed_field @property def _private_property(self) -> int: return -self.foo m = Model(foo=1) print(repr(m)) #> Model(foo=1)` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `func` | `PropertyT \| None` | the function to wrap. | `None` | | `alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | alias to use when serializing this computed field, only used when `by_alias=True` | `None` | | `alias_priority` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | priority of the alias. This affects whether an alias generator is used | `None` | | `title` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Title to use when including this computed field in JSON Schema | `None` | | `field_title_generator` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns title for it. | `None` | | `description` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Description to use when including this computed field in JSON Schema, defaults to the function's docstring | `None` | | `deprecated` | `Deprecated \| [str](https://docs.python.org/3/library/stdtypes.html#str) \| [bool](https://docs.python.org/3/library/functions.html#bool) \| None` | A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport). to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the `deprecated` decorator. | `None` | | `examples` | `[list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Example values to use when including this computed field in JSON Schema | `None` | | `json_schema_extra` | `JsonDict \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] \| None` | A dict or callable to provide extra JSON schema properties. | `None` | | `repr` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | whether to include this computed field in model repr. Default is `False` for private properties and `True` for public properties. | `None` | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | optional return for serialization logic to expect when serializing to JSON, if included this must be correct, otherwise a `TypeError` is raised. If you don't include a return type Any is used, which does runtime introspection to handle arbitrary objects. | `PydanticUndefined` | Returns: | Type | Description | | --- | --- | | `PropertyT \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[PropertyT], PropertyT]` | A proxy wrapper for the property. | Source code in `pydantic/fields.py` | | | | --- | --- | | 1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542 | ``def computed_field( func: PropertyT \| None = None, /, *, alias: str \| None = None, alias_priority: int \| None = None, title: str \| None = None, field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] \| None = None, description: str \| None = None, deprecated: Deprecated \| str \| bool \| None = None, examples: list[Any] \| None = None, json_schema_extra: JsonDict \| typing.Callable[[JsonDict], None] \| None = None, repr: bool \| None = None, return_type: Any = PydanticUndefined, ) -> PropertyT \| typing.Callable[[PropertyT], PropertyT]: """!!! abstract "Usage Documentation" [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator) Decorator to include `property` and `cached_property` when serializing models or dataclasses. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. ```python from pydantic import BaseModel, computed_field class Rectangle(BaseModel): width: int length: int @computed_field @property def area(self) -> int: return self.width * self.length print(Rectangle(width=3, length=2).model_dump()) #> {'width': 3, 'length': 2, 'area': 6} ``` If applied to functions not yet decorated with `@property` or `@cached_property`, the function is automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE, and confuse static type checkers, thus explicit use of `@property` is recommended. !!! warning "Mypy Warning" Even with the `@property` or `@cached_property` applied to your function before `@computed_field`, mypy may throw a `Decorated property not supported` error. See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information. To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line. [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error. ```python import random from pydantic import BaseModel, computed_field class Square(BaseModel): width: float @computed_field def area(self) -> float: # converted to a `property` by `computed_field` return round(self.width**2, 2) @area.setter def area(self, new_area: float) -> None: self.width = new_area**0.5 @computed_field(alias='the magic number', repr=False) def random_number(self) -> int: return random.randint(0, 1_000) square = Square(width=1.3) # `random_number` does not appear in representation print(repr(square)) #> Square(width=1.3, area=1.69) print(square.random_number) #> 3 square.area = 4 print(square.model_dump_json(by_alias=True)) #> {"width":2.0,"area":4.0,"the magic number":3} ``` !!! warning "Overriding with `computed_field`" You can't override a field from a parent class with a `computed_field` in the child class. `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either. See the example below: ```python from pydantic import BaseModel, computed_field class Parent(BaseModel): a: str try: class Child(Parent): @computed_field @property def a(self) -> str: return 'new a' except TypeError as e: print(e) ''' Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible. ''' ``` Private properties decorated with `@computed_field` have `repr=False` by default. ```python from functools import cached_property from pydantic import BaseModel, computed_field class Model(BaseModel): foo: int @computed_field @cached_property def _private_cached_property(self) -> int: return -self.foo @computed_field @property def _private_property(self) -> int: return -self.foo m = Model(foo=1) print(repr(m)) #> Model(foo=1) ``` Args: func: the function to wrap. alias: alias to use when serializing this computed field, only used when `by_alias=True` alias_priority: priority of the alias. This affects whether an alias generator is used title: Title to use when including this computed field in JSON Schema field_title_generator: A callable that takes a field name and returns title for it. description: Description to use when including this computed field in JSON Schema, defaults to the function's docstring deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport). to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the `deprecated` decorator. examples: Example values to use when including this computed field in JSON Schema json_schema_extra: A dict or callable to provide extra JSON schema properties. repr: whether to include this computed field in model repr. Default is `False` for private properties and `True` for public properties. return_type: optional return for serialization logic to expect when serializing to JSON, if included this must be correct, otherwise a `TypeError` is raised. If you don't include a return type Any is used, which does runtime introspection to handle arbitrary objects. Returns: A proxy wrapper for the property. """ def dec(f: Any) -> Any: nonlocal description, deprecated, return_type, alias_priority unwrapped = _decorators.unwrap_wrapped_function(f) if description is None and unwrapped.__doc__: description = inspect.cleandoc(unwrapped.__doc__) if deprecated is None and hasattr(unwrapped, '__deprecated__'): deprecated = unwrapped.__deprecated__ # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now f = _decorators.ensure_property(f) alias_priority = (alias_priority or 2) if alias is not None else None if repr is None: repr_: bool = not _wrapped_property_is_private(property_=f) else: repr_ = repr dec_info = ComputedFieldInfo( f, return_type, alias, alias_priority, title, field_title_generator, description, deprecated, examples, json_schema_extra, repr_, ) return _decorators.PydanticDescriptorProxy(f, dec_info) if func is None: return dec else: return dec(func)`` | ComputedFieldInfo `dataclass` [¶](#pydantic.fields.ComputedFieldInfo "Permanent link") --------------------------------------------------------------------------------------- `ComputedFieldInfo( wrapped_property: [property](https://docs.python.org/3/library/functions.html#property) , return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , alias: [str](https://docs.python.org/3/library/stdtypes.html#str) | None, alias_priority: [int](https://docs.python.org/3/library/functions.html#int) | None, title: [str](https://docs.python.org/3/library/stdtypes.html#str) | None, field_title_generator: ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] | None ), description: [str](https://docs.python.org/3/library/stdtypes.html#str) | None, deprecated: Deprecated | [str](https://docs.python.org/3/library/stdtypes.html#str) | [bool](https://docs.python.org/3/library/functions.html#bool) | None, examples: [list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None, json_schema_extra: ( JsonDict | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] | None ), repr: [bool](https://docs.python.org/3/library/functions.html#bool) , )` A container for data from `@computed_field` so that we can access it while building the pydantic-core schema. Attributes: | Name | Type | Description | | --- | --- | --- | | `decorator_repr` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | A class variable representing the decorator string, '@computed\_field'. | | `wrapped_property` | `[property](https://docs.python.org/3/library/functions.html#property) ` | The wrapped computed field property. | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The type of the computed field property's return value. | | `alias` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The alias of the property to be used during serialization. | | `alias_priority` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | The priority of the alias. This affects whether an alias generator is used. | | `title` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Title of the computed field to include in the serialization JSON schema. | | `field_title_generator` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[str](https://docs.python.org/3/library/stdtypes.html#str) , [ComputedFieldInfo](#pydantic.fields.ComputedFieldInfo "pydantic.fields.ComputedFieldInfo") ], [str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | A callable that takes a field name and returns title for it. | | `description` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | Description of the computed field to include in the serialization JSON schema. | | `deprecated` | `Deprecated \| [str](https://docs.python.org/3/library/stdtypes.html#str) \| [bool](https://docs.python.org/3/library/functions.html#bool) \| None` | A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. | | `examples` | `[list](https://docs.python.org/3/glossary.html#term-list) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | Example values of the computed field to include in the serialization JSON schema. | | `json_schema_extra` | `JsonDict \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[JsonDict], None] \| None` | A dict or callable to provide extra JSON schema properties. | | `repr` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | A boolean indicating whether to include the field in the **repr** output. | ### deprecation\_message `property` [¶](#pydantic.fields.ComputedFieldInfo.deprecation_message "Permanent link") `deprecation_message: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The deprecation message to be emitted, or `None` if not set. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Functional Serializers - Pydantic Functional Serializers ====================== This module contains related classes and functions for serialization. FieldPlainSerializer `module-attribute` [¶](#pydantic.functional_serializers.FieldPlainSerializer "Permanent link") -------------------------------------------------------------------------------------------------------------------- `FieldPlainSerializer: TypeAlias = ( "core_schema.SerializerFunction | _Partial" )` A field serializer method or function in `plain` mode. FieldWrapSerializer `module-attribute` [¶](#pydantic.functional_serializers.FieldWrapSerializer "Permanent link") ------------------------------------------------------------------------------------------------------------------ `FieldWrapSerializer: TypeAlias = ( "core_schema.WrapSerializerFunction | _Partial" )` A field serializer method or function in `wrap` mode. FieldSerializer `module-attribute` [¶](#pydantic.functional_serializers.FieldSerializer "Permanent link") ---------------------------------------------------------------------------------------------------------- `FieldSerializer: TypeAlias = ( "FieldPlainSerializer | FieldWrapSerializer" )` A field serializer method or function. ModelPlainSerializerWithInfo `module-attribute` [¶](#pydantic.functional_serializers.ModelPlainSerializerWithInfo "Permanent link") ------------------------------------------------------------------------------------------------------------------------------------ `ModelPlainSerializerWithInfo: TypeAlias = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , [SerializationInfo](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo "pydantic_core.core_schema.SerializationInfo") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` A model serializer method with the `info` argument, in `plain` mode. ModelPlainSerializerWithoutInfo `module-attribute` [¶](#pydantic.functional_serializers.ModelPlainSerializerWithoutInfo "Permanent link") ------------------------------------------------------------------------------------------------------------------------------------------ `ModelPlainSerializerWithoutInfo: TypeAlias = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` A model serializer method without the `info` argument, in `plain` mode. ModelPlainSerializer `module-attribute` [¶](#pydantic.functional_serializers.ModelPlainSerializer "Permanent link") -------------------------------------------------------------------------------------------------------------------- `ModelPlainSerializer: TypeAlias = ( "ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfo" )` A model serializer method in `plain` mode. ModelWrapSerializerWithInfo `module-attribute` [¶](#pydantic.functional_serializers.ModelWrapSerializerWithInfo "Permanent link") ---------------------------------------------------------------------------------------------------------------------------------- `ModelWrapSerializerWithInfo: TypeAlias = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , SerializerFunctionWrapHandler, [SerializationInfo](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo "pydantic_core.core_schema.SerializationInfo") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ]` A model serializer method with the `info` argument, in `wrap` mode. ModelWrapSerializerWithoutInfo `module-attribute` [¶](#pydantic.functional_serializers.ModelWrapSerializerWithoutInfo "Permanent link") ---------------------------------------------------------------------------------------------------------------------------------------- `ModelWrapSerializerWithoutInfo: TypeAlias = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , SerializerFunctionWrapHandler], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` A model serializer method without the `info` argument, in `wrap` mode. ModelWrapSerializer `module-attribute` [¶](#pydantic.functional_serializers.ModelWrapSerializer "Permanent link") ------------------------------------------------------------------------------------------------------------------ `ModelWrapSerializer: TypeAlias = ( "ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfo" )` A model serializer method in `wrap` mode. PlainSerializer `dataclass` [¶](#pydantic.functional_serializers.PlainSerializer "Permanent link") --------------------------------------------------------------------------------------------------- `PlainSerializer( func: SerializerFunction, return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", )` Plain serializers use a function to modify the output of serialization. This is particularly helpful when you want to customize the serialization for annotated types. Consider an input of `list`, which will be serialized into a space-delimited string. `from typing import Annotated from pydantic import BaseModel, PlainSerializer CustomStr = Annotated[ list, PlainSerializer(lambda x: ' '.join(x), return_type=str) ] class StudentModel(BaseModel): courses: CustomStr student = StudentModel(courses=['Math', 'Chemistry', 'English']) print(student.model_dump()) #> {'courses': 'Math Chemistry English'}` Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `SerializerFunction` | The serializer function. | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The return type for the function. If omitted it will be inferred from the type annotation. | | `when_used` | `[WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") ` | Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. | WrapSerializer `dataclass` [¶](#pydantic.functional_serializers.WrapSerializer "Permanent link") ------------------------------------------------------------------------------------------------- `WrapSerializer( func: WrapSerializerFunction, return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", )` Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization. For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic. ``from datetime import datetime, timezone from typing import Annotated, Any from pydantic import BaseModel, WrapSerializer class EventDatetime(BaseModel): start: datetime end: datetime def convert_to_utc(value: Any, handler, info) -> dict[str, datetime]: # Note that `handler` can actually help serialize the `value` for # further custom serialization in case it's a subclass. partial_result = handler(value, info) if info.mode == 'json': return { k: datetime.fromisoformat(v).astimezone(timezone.utc) for k, v in partial_result.items() } return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()} UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)] class EventModel(BaseModel): event_datetime: UTCEventDatetime dt = EventDatetime( start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00' ) event = EventModel(event_datetime=dt) print(event.model_dump()) ''' { 'event_datetime': { 'start': datetime.datetime( 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc ), 'end': datetime.datetime( 2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc ), } } ''' print(event.model_dump_json()) ''' {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}} '''`` Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `WrapSerializerFunction` | The serializer function to be wrapped. | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The return type for the function. If omitted it will be inferred from the type annotation. | | `when_used` | `[WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") ` | Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. | field\_serializer [¶](#pydantic.functional_serializers.field_serializer "Permanent link") ------------------------------------------------------------------------------------------ `field_serializer( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["wrap"], return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ..., when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = ..., check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = ..., ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_FieldWrapSerializerT], _FieldWrapSerializerT ]` `field_serializer( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["plain"] = ..., return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ..., when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = ..., check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = ..., ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_FieldPlainSerializerT], _FieldPlainSerializerT ]` `field_serializer( *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["plain", "wrap"] = "plain", return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> ( [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_FieldWrapSerializerT], _FieldWrapSerializerT] | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_FieldPlainSerializerT], _FieldPlainSerializerT ] )` Decorator that enables custom field serialization. In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list. `from typing import Set from pydantic import BaseModel, field_serializer class StudentModel(BaseModel): name: str = 'Jane' courses: Set[str] @field_serializer('courses', when_used='json') def serialize_courses_in_order(self, courses: Set[str]): return sorted(courses) student = StudentModel(courses={'Math', 'Chemistry', 'English'}) print(student.model_dump_json()) #> {"name":"Jane","courses":["Chemistry","English","Math"]}` See [Custom serializers](../../concepts/serialization/#custom-serializers) for more information. Four signatures are supported: * `(self, value: Any, info: FieldSerializationInfo)` * `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` * `(value: Any, info: SerializationInfo)` * `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `fields` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | Which field(s) the method should be called on. | `()` | | `mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['plain', 'wrap']` | The serialization mode.

* `plain` means the function will be called instead of the default serialization logic,
* `wrap` means the function will be called with an argument to optionally call the default serialization logic. | `'plain'` | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | Optional return type for the function, if omitted it will be inferred from the type annotation. | `PydanticUndefined` | | `when_used` | `[WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") ` | Determines the serializer will be used for serialization. | `'always'` | | `check_fields` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to check that the fields actually exist on the model. | `None` | Returns: | Type | Description | | --- | --- | | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_FieldWrapSerializerT], _FieldWrapSerializerT] \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_FieldPlainSerializerT], _FieldPlainSerializerT]` | The decorator function. | Source code in `pydantic/functional_serializers.py` | | | | --- | --- | | 231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297 | ``def field_serializer( *fields: str, mode: Literal['plain', 'wrap'] = 'plain', return_type: Any = PydanticUndefined, when_used: WhenUsed = 'always', check_fields: bool \| None = None, ) -> ( Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT] \| Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT] ): """Decorator that enables custom field serialization. In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list. ```python from typing import Set from pydantic import BaseModel, field_serializer class StudentModel(BaseModel): name: str = 'Jane' courses: Set[str] @field_serializer('courses', when_used='json') def serialize_courses_in_order(self, courses: Set[str]): return sorted(courses) student = StudentModel(courses={'Math', 'Chemistry', 'English'}) print(student.model_dump_json()) #> {"name":"Jane","courses":["Chemistry","English","Math"]} ``` See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information. Four signatures are supported: - `(self, value: Any, info: FieldSerializationInfo)` - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` - `(value: Any, info: SerializationInfo)` - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` Args: fields: Which field(s) the method should be called on. mode: The serialization mode. - `plain` means the function will be called instead of the default serialization logic, - `wrap` means the function will be called with an argument to optionally call the default serialization logic. return_type: Optional return type for the function, if omitted it will be inferred from the type annotation. when_used: Determines the serializer will be used for serialization. check_fields: Whether to check that the fields actually exist on the model. Returns: The decorator function. """ def dec(f: FieldSerializer) -> _decorators.PydanticDescriptorProxy[Any]: dec_info = _decorators.FieldSerializerDecoratorInfo( fields=fields, mode=mode, return_type=return_type, when_used=when_used, check_fields=check_fields, ) return _decorators.PydanticDescriptorProxy(f, dec_info) # pyright: ignore[reportArgumentType] return dec # pyright: ignore[reportReturnType]`` | model\_serializer [¶](#pydantic.functional_serializers.model_serializer "Permanent link") ------------------------------------------------------------------------------------------ `model_serializer( f: _ModelPlainSerializerT, ) -> _ModelPlainSerializerT` `model_serializer( *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["wrap"], when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ... ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelWrapSerializerT], _ModelWrapSerializerT ]` `model_serializer( *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["plain"] = ..., when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ... ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelPlainSerializerT], _ModelPlainSerializerT ]` `model_serializer( f: ( _ModelPlainSerializerT | _ModelWrapSerializerT | None ) = None, /, *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["plain", "wrap"] = "plain", when_used: [WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") = "always", return_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, ) -> ( _ModelPlainSerializerT | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelWrapSerializerT], _ModelWrapSerializerT ] | [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelPlainSerializerT], _ModelPlainSerializerT ] )` Decorator that enables custom model serialization. This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields. An example would be to serialize temperature to the same temperature scale, such as degrees Celsius. `from typing import Literal from pydantic import BaseModel, model_serializer class TemperatureModel(BaseModel): unit: Literal['C', 'F'] value: int @model_serializer() def serialize_model(self): if self.unit == 'F': return {'unit': 'C', 'value': int((self.value - 32) / 1.8)} return {'unit': self.unit, 'value': self.value} temperature = TemperatureModel(unit='F', value=212) print(temperature.model_dump()) #> {'unit': 'C', 'value': 100}` Two signatures are supported for `mode='plain'`, which is the default: * `(self)` * `(self, info: SerializationInfo)` And two other signatures for `mode='wrap'`: * `(self, nxt: SerializerFunctionWrapHandler)` * `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` See [Custom serializers](../../concepts/serialization/#custom-serializers) for more information. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `f` | `_ModelPlainSerializerT \| _ModelWrapSerializerT \| None` | The function to be decorated. | `None` | | `mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['plain', 'wrap']` | The serialization mode.

* `'plain'` means the function will be called instead of the default serialization logic
* `'wrap'` means the function will be called with an argument to optionally call the default serialization logic. | `'plain'` | | `when_used` | `[WhenUsed](../pydantic_core_schema/#pydantic_core.core_schema.WhenUsed "pydantic_core.core_schema.WhenUsed") ` | Determines when this serializer should be used. | `'always'` | | `return_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The return type for the function. If omitted it will be inferred from the type annotation. | `PydanticUndefined` | Returns: | Type | Description | | --- | --- | | `_ModelPlainSerializerT \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_ModelWrapSerializerT], _ModelWrapSerializerT] \| [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_ModelPlainSerializerT], _ModelPlainSerializerT]` | The decorator function. | Source code in `pydantic/functional_serializers.py` | | | | --- | --- | | 346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417 | ``def model_serializer( f: _ModelPlainSerializerT \| _ModelWrapSerializerT \| None = None, /, *, mode: Literal['plain', 'wrap'] = 'plain', when_used: WhenUsed = 'always', return_type: Any = PydanticUndefined, ) -> ( _ModelPlainSerializerT \| Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] \| Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT] ): """Decorator that enables custom model serialization. This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields. An example would be to serialize temperature to the same temperature scale, such as degrees Celsius. ```python from typing import Literal from pydantic import BaseModel, model_serializer class TemperatureModel(BaseModel): unit: Literal['C', 'F'] value: int @model_serializer() def serialize_model(self): if self.unit == 'F': return {'unit': 'C', 'value': int((self.value - 32) / 1.8)} return {'unit': self.unit, 'value': self.value} temperature = TemperatureModel(unit='F', value=212) print(temperature.model_dump()) #> {'unit': 'C', 'value': 100} ``` Two signatures are supported for `mode='plain'`, which is the default: - `(self)` - `(self, info: SerializationInfo)` And two other signatures for `mode='wrap'`: - `(self, nxt: SerializerFunctionWrapHandler)` - `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information. Args: f: The function to be decorated. mode: The serialization mode. - `'plain'` means the function will be called instead of the default serialization logic - `'wrap'` means the function will be called with an argument to optionally call the default serialization logic. when_used: Determines when this serializer should be used. return_type: The return type for the function. If omitted it will be inferred from the type annotation. Returns: The decorator function. """ def dec(f: ModelSerializer) -> _decorators.PydanticDescriptorProxy[Any]: dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used) return _decorators.PydanticDescriptorProxy(f, dec_info) if f is None: return dec # pyright: ignore[reportReturnType] else: return dec(f) # pyright: ignore[reportReturnType]`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # pydantic_core - Pydantic pydantic\_core ============== \_\_version\_\_ `module-attribute` [¶](#pydantic_core.__version__ "Permanent link") ------------------------------------------------------------------------------------ `__version__: [str](https://docs.python.org/3/library/stdtypes.html#str)` SchemaValidator [¶](#pydantic_core.SchemaValidator "Permanent link") --------------------------------------------------------------------- `SchemaValidator( schema: CoreSchema, config: [CoreConfig](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig "pydantic_core.core_schema.CoreConfig") | None = None )` `SchemaValidator` is the Python wrapper for `pydantic-core`'s Rust validation logic, internally it owns one `CombinedValidator` which may in turn own more `CombinedValidator`s which make up the full schema validator. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `schema` | `CoreSchema` | The `CoreSchema` to use for validation. | _required_ | | `config` | `[CoreConfig](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig "pydantic_core.core_schema.CoreConfig") \| None` | Optionally a [`CoreConfig`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
to configure validation. | `None` | ### title `property` [¶](#pydantic_core.SchemaValidator.title "Permanent link") `title: [str](https://docs.python.org/3/library/stdtypes.html#str)` The title of the schema, as used in the heading of [`ValidationError.__str__()`](#pydantic_core.ValidationError) . ### validate\_python [¶](#pydantic_core.SchemaValidator.validate_python "Permanent link") `validate_python( input: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, from_attributes: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, self_instance: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, allow_partial: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["off", "on", "trailing-strings"] ) = False, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Validate a Python object against the schema and return the validated object. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `input` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The Python object to validate. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the object in strict mode. If `None`, the value of [`CoreConfig.strict`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `from_attributes` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate objects as inputs to models by extracting attributes. If `None`, the value of [`CoreConfig.from_attributes`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for validation, this is passed to functional validators as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo.context)
. | `None` | | `self_instance` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | An instance of a model set attributes on from validation, this is used when running validation from the `__init__` method of a model. | `None` | | `allow_partial` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['off', 'on', 'trailing-strings']` | Whether to allow partial validation; if `True` errors in the last element of sequences and mappings are ignored. `'trailing-strings'` means any final unfinished JSON string is included in the result. | `False` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](#pydantic_core.ValidationError "pydantic_core._pydantic_core.ValidationError") ` | If validation fails. | | `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` | Other error types maybe raised if internal errors occur. | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The validated object. | ### isinstance\_python [¶](#pydantic_core.SchemaValidator.isinstance_python "Permanent link") `isinstance_python( input: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, from_attributes: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, self_instance: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [bool](https://docs.python.org/3/library/functions.html#bool)` Similar to [`validate_python()`](#pydantic_core.SchemaValidator.validate_python) but returns a boolean. Arguments match `validate_python()`. This method will not raise `ValidationError`s but will raise internal errors. Returns: | Type | Description | | --- | --- | | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | `True` if validation succeeds, `False` if validation fails. | ### validate\_json [¶](#pydantic_core.SchemaValidator.validate_json "Permanent link") `validate_json( input: [str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, self_instance: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, allow_partial: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["off", "on", "trailing-strings"] ) = False, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Validate JSON data directly against the schema and return the validated Python object. This method should be significantly faster than `validate_python(json.loads(json_data))` as it avoids the need to create intermediate Python objects It also handles constructing the correct Python type even in strict mode, where `validate_python(json.loads(json_data))` would fail validation. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `input` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) \| [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) ` | The JSON data to validate. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the object in strict mode. If `None`, the value of [`CoreConfig.strict`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for validation, this is passed to functional validators as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo.context)
. | `None` | | `self_instance` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | An instance of a model set attributes on from validation. | `None` | | `allow_partial` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['off', 'on', 'trailing-strings']` | Whether to allow partial validation; if `True` incomplete JSON will be parsed successfully and errors in the last element of sequences and mappings are ignored. `'trailing-strings'` means any final unfinished JSON string is included in the result. | `False` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](#pydantic_core.ValidationError "pydantic_core._pydantic_core.ValidationError") ` | If validation fails or if the JSON data is invalid. | | `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` | Other error types maybe raised if internal errors occur. | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The validated Python object. | ### validate\_strings [¶](#pydantic_core.SchemaValidator.validate_strings "Permanent link") `validate_strings( input: _StringInput, *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, allow_partial: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["off", "on", "trailing-strings"] ) = False, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Validate a string against the schema and return the validated Python object. This is similar to `validate_json` but applies to scenarios where the input will be a string but not JSON data, e.g. URL fragments, query parameters, etc. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `input` | `_StringInput` | The input as a string, or bytes/bytearray if `strict=False`. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the object in strict mode. If `None`, the value of [`CoreConfig.strict`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for validation, this is passed to functional validators as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo.context)
. | `None` | | `allow_partial` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['off', 'on', 'trailing-strings']` | Whether to allow partial validation; if `True` errors in the last element of sequences and mappings are ignored. `'trailing-strings'` means any final unfinished JSON string is included in the result. | `False` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](#pydantic_core.ValidationError "pydantic_core._pydantic_core.ValidationError") ` | If validation fails or if the JSON data is invalid. | | `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` | Other error types maybe raised if internal errors occur. | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The validated Python object. | ### validate\_assignment [¶](#pydantic_core.SchemaValidator.validate_assignment "Permanent link") `validate_assignment( obj: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , field_name: [str](https://docs.python.org/3/library/stdtypes.html#str) , field_value: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, from_attributes: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, by_name: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None ) -> ( [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None, [set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]] )` Validate an assignment to a field on a model. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `obj` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The model instance being assigned to. | _required_ | | `field_name` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The name of the field to validate assignment for. | _required_ | | `field_value` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The value to assign to the field. | _required_ | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the object in strict mode. If `None`, the value of [`CoreConfig.strict`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `from_attributes` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate objects as inputs to models by extracting attributes. If `None`, the value of [`CoreConfig.from_attributes`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for validation, this is passed to functional validators as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo.context)
. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's alias when validating against the provided input data. | `None` | | `by_name` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the field's name when validating against the provided input data. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](#pydantic_core.ValidationError "pydantic_core._pydantic_core.ValidationError") ` | If validation fails. | | `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` | Other error types maybe raised if internal errors occur. | Returns: | Type | Description | | --- | --- | | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None, [set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ]]` | Either the model dict or a tuple of `(model_data, model_extra, fields_set)` | ### get\_default\_value [¶](#pydantic_core.SchemaValidator.get_default_value "Permanent link") `get_default_value( *, strict: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = None ) -> [Some](#pydantic_core.Some "pydantic_core._pydantic_core.Some") | None` Get the default value for the schema, including running default value validation. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `strict` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to validate the default value in strict mode. If `None`, the value of [`CoreConfig.strict`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
is used. | `None` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The context to use for validation, this is passed to functional validators as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo.context)
. | `None` | Raises: | Type | Description | | --- | --- | | `[ValidationError](#pydantic_core.ValidationError "pydantic_core._pydantic_core.ValidationError") ` | If validation fails. | | `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` | Other error types maybe raised if internal errors occur. | Returns: | Type | Description | | --- | --- | | `[Some](#pydantic_core.Some "pydantic_core._pydantic_core.Some") \| None` | `None` if the schema has no default value, otherwise a [`Some`](#pydantic_core.Some)
containing the default. | SchemaSerializer [¶](#pydantic_core.SchemaSerializer "Permanent link") ----------------------------------------------------------------------- `SchemaSerializer( schema: CoreSchema, config: [CoreConfig](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig "pydantic_core.core_schema.CoreConfig") | None = None )` `SchemaSerializer` is the Python wrapper for `pydantic-core`'s Rust serialization logic, internally it owns one `CombinedSerializer` which may in turn own more `CombinedSerializer`s which make up the full schema serializer. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `schema` | `CoreSchema` | The `CoreSchema` to use for serialization. | _required_ | | `config` | `[CoreConfig](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig "pydantic_core.core_schema.CoreConfig") \| None` | Optionally a [`CoreConfig`](../pydantic_core_schema/#pydantic_core.core_schema.CoreConfig)
to to configure serialization. | `None` | ### to\_python [¶](#pydantic_core.SchemaSerializer.to_python "Permanent link") `to_python( value: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, mode: [str](https://docs.python.org/3/library/stdtypes.html#str) | None = None, include: _IncEx | None = None, exclude: _IncEx | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, exclude_unset: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_defaults: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, warnings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["none", "warn", "error"] ) = True, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Serialize/marshal a Python object to a Python object including transforming and filtering data. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The Python object to serialize. | _required_ | | `mode` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| None` | The serialization mode to use, either `'python'` or `'json'`, defaults to `'python'`. In JSON mode, all values are converted to JSON compatible types, e.g. `None`, `int`, `float`, `str`, `list`, `dict`. | `None` | | `include` | `_IncEx \| None` | A set of fields to include, if `None` all fields are included. | `None` | | `exclude` | `_IncEx \| None` | A set of fields to exclude, if `None` no fields are excluded. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the alias names of fields. | `None` | | `exclude_unset` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are not set, e.g. are not included in `__pydantic_fields_set__`. | `False` | | `exclude_defaults` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are equal to their default value. | `False` | | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` | | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to enable serialization and validation round-trip support. | `False` | | `warnings` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['none', 'warn', 'error']` | How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
. | `True` | | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered, if `None` a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
error is raised. | `None` | | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for serialization, this is passed to functional serializers as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo.context)
. | `None` | Raises: | Type | Description | | --- | --- | | `[PydanticSerializationError](#pydantic_core.PydanticSerializationError "pydantic_core._pydantic_core.PydanticSerializationError") ` | If serialization fails and no `fallback` function is provided. | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The serialized Python object. | ### to\_json [¶](#pydantic_core.SchemaSerializer.to_json "Permanent link") `to_json( value: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, indent: [int](https://docs.python.org/3/library/functions.html#int) | None = None, include: _IncEx | None = None, exclude: _IncEx | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, exclude_unset: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_defaults: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, warnings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["none", "warn", "error"] ) = True, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None ) -> [bytes](https://docs.python.org/3/library/stdtypes.html#bytes)` Serialize a Python object to JSON including transforming and filtering data. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The Python object to serialize. | _required_ | | `indent` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided. | `None` | | `include` | `_IncEx \| None` | A set of fields to include, if `None` all fields are included. | `None` | | `exclude` | `_IncEx \| None` | A set of fields to exclude, if `None` no fields are excluded. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to use the alias names of fields. | `None` | | `exclude_unset` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are not set, e.g. are not included in `__pydantic_fields_set__`. | `False` | | `exclude_defaults` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that are equal to their default value. | `False` | | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` | | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to enable serialization and validation round-trip support. | `False` | | `warnings` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['none', 'warn', 'error']` | How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
. | `True` | | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered, if `None` a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
error is raised. | `None` | | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for serialization, this is passed to functional serializers as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo.context)
. | `None` | Raises: | Type | Description | | --- | --- | | `[PydanticSerializationError](#pydantic_core.PydanticSerializationError "pydantic_core._pydantic_core.PydanticSerializationError") ` | If serialization fails and no `fallback` function is provided. | Returns: | Type | Description | | --- | --- | | `[bytes](https://docs.python.org/3/library/stdtypes.html#bytes) ` | JSON bytes. | ValidationError [¶](#pydantic_core.ValidationError "Permanent link") --------------------------------------------------------------------- Bases: `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` `ValidationError` is the exception raised by `pydantic-core` when validation fails, it contains a list of errors which detail why validation failed. ### title `property` [¶](#pydantic_core.ValidationError.title "Permanent link") `title: [str](https://docs.python.org/3/library/stdtypes.html#str)` The title of the error, as used in the heading of `str(validation_error)`. ### from\_exception\_data `classmethod` [¶](#pydantic_core.ValidationError.from_exception_data "Permanent link") `from_exception_data( title: [str](https://docs.python.org/3/library/stdtypes.html#str) , line_errors: [list](https://docs.python.org/3/glossary.html#term-list) [[InitErrorDetails](#pydantic_core.InitErrorDetails "pydantic_core.InitErrorDetails") ], input_type: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["python", "json"] = "python", hide_input: [bool](https://docs.python.org/3/library/functions.html#bool) = False, ) -> Self` Python constructor for a Validation Error. The API for constructing validation errors will probably change in the future, hence the static method rather than `__init__`. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `title` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The title of the error, as used in the heading of `str(validation_error)` | _required_ | | `line_errors` | `[list](https://docs.python.org/3/glossary.html#term-list) [[InitErrorDetails](#pydantic_core.InitErrorDetails "pydantic_core.InitErrorDetails") ]` | A list of [`InitErrorDetails`](#pydantic_core.InitErrorDetails)
which contain information about errors that occurred during validation. | _required_ | | `input_type` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['python', 'json']` | Whether the error is for a Python object or JSON. | `'python'` | | `hide_input` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to hide the input value in the error message. | `False` | ### error\_count [¶](#pydantic_core.ValidationError.error_count "Permanent link") `error_count() -> [int](https://docs.python.org/3/library/functions.html#int)` Returns: | Type | Description | | --- | --- | | `[int](https://docs.python.org/3/library/functions.html#int) ` | The number of errors in the validation error. | ### errors [¶](#pydantic_core.ValidationError.errors "Permanent link") `errors( *, include_url: [bool](https://docs.python.org/3/library/functions.html#bool) = True, include_context: [bool](https://docs.python.org/3/library/functions.html#bool) = True, include_input: [bool](https://docs.python.org/3/library/functions.html#bool) = True ) -> [list](https://docs.python.org/3/glossary.html#term-list) [[ErrorDetails](#pydantic_core.ErrorDetails "pydantic_core.ErrorDetails") ]` Details about each error in the validation error. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `include_url` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include a URL to documentation on the error each error. | `True` | | `include_context` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include the context of each error. | `True` | | `include_input` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include the input value of each error. | `True` | Returns: | Type | Description | | --- | --- | | `[list](https://docs.python.org/3/glossary.html#term-list) [[ErrorDetails](#pydantic_core.ErrorDetails "pydantic_core.ErrorDetails") ]` | A list of [`ErrorDetails`](#pydantic_core.ErrorDetails)
for each error in the validation error. | ### json [¶](#pydantic_core.ValidationError.json "Permanent link") `json( *, indent: [int](https://docs.python.org/3/library/functions.html#int) | None = None, include_url: [bool](https://docs.python.org/3/library/functions.html#bool) = True, include_context: [bool](https://docs.python.org/3/library/functions.html#bool) = True, include_input: [bool](https://docs.python.org/3/library/functions.html#bool) = True ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Same as [`errors()`](#pydantic_core.ValidationError.errors) but returns a JSON string. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `indent` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | The number of spaces to indent the JSON by, or `None` for no indentation - compact JSON. | `None` | | `include_url` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include a URL to documentation on the error each error. | `True` | | `include_context` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include the context of each error. | `True` | | `include_input` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to include the input value of each error. | `True` | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | a JSON string. | ErrorDetails [¶](#pydantic_core.ErrorDetails "Permanent link") --------------------------------------------------------------- Bases: `[TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict "typing.TypedDict") ` ### type `instance-attribute` [¶](#pydantic_core.ErrorDetails.type "Permanent link") `type: [str](https://docs.python.org/3/library/stdtypes.html#str)` The type of error that occurred, this is an identifier designed for programmatic use that will change rarely or never. `type` is unique for each error message, and can hence be used as an identifier to build custom error messages. ### loc `instance-attribute` [¶](#pydantic_core.ErrorDetails.loc "Permanent link") `loc: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , ...]` Tuple of strings and ints identifying where in the schema the error occurred. ### msg `instance-attribute` [¶](#pydantic_core.ErrorDetails.msg "Permanent link") `msg: [str](https://docs.python.org/3/library/stdtypes.html#str)` A human readable error message. ### input `instance-attribute` [¶](#pydantic_core.ErrorDetails.input "Permanent link") `input: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` The input data at this `loc` that caused the error. ### ctx `instance-attribute` [¶](#pydantic_core.ErrorDetails.ctx "Permanent link") `ctx: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]]` Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward. ### url `instance-attribute` [¶](#pydantic_core.ErrorDetails.url "Permanent link") `url: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` The documentation URL giving information about the error. No URL is available if a [`PydanticCustomError`](#pydantic_core.PydanticCustomError) is used. InitErrorDetails [¶](#pydantic_core.InitErrorDetails "Permanent link") ----------------------------------------------------------------------- Bases: `[TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict "typing.TypedDict") ` ### type `instance-attribute` [¶](#pydantic_core.InitErrorDetails.type "Permanent link") `type: [str](https://docs.python.org/3/library/stdtypes.html#str) | [PydanticCustomError](#pydantic_core.PydanticCustomError "pydantic_core._pydantic_core.PydanticCustomError")` The type of error that occurred, this should be a "slug" identifier that changes rarely or never. ### loc `instance-attribute` [¶](#pydantic_core.InitErrorDetails.loc "Permanent link") `loc: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , ...]]` Tuple of strings and ints identifying where in the schema the error occurred. ### input `instance-attribute` [¶](#pydantic_core.InitErrorDetails.input "Permanent link") `input: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` The input data at this `loc` that caused the error. ### ctx `instance-attribute` [¶](#pydantic_core.InitErrorDetails.ctx "Permanent link") `ctx: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]]` Values which are required to render the error message, and could hence be useful in rendering custom error messages. Also useful for passing custom error data forward. SchemaError [¶](#pydantic_core.SchemaError "Permanent link") ------------------------------------------------------------- Bases: `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` Information about errors that occur while building a [`SchemaValidator`](#pydantic_core.SchemaValidator) or [`SchemaSerializer`](#pydantic_core.SchemaSerializer) . ### error\_count [¶](#pydantic_core.SchemaError.error_count "Permanent link") `error_count() -> [int](https://docs.python.org/3/library/functions.html#int)` Returns: | Type | Description | | --- | --- | | `[int](https://docs.python.org/3/library/functions.html#int) ` | The number of errors in the schema. | ### errors [¶](#pydantic_core.SchemaError.errors "Permanent link") `errors() -> [list](https://docs.python.org/3/glossary.html#term-list) [[ErrorDetails](#pydantic_core.ErrorDetails "pydantic_core.ErrorDetails") ]` Returns: | Type | Description | | --- | --- | | `[list](https://docs.python.org/3/glossary.html#term-list) [[ErrorDetails](#pydantic_core.ErrorDetails "pydantic_core.ErrorDetails") ]` | A list of [`ErrorDetails`](#pydantic_core.ErrorDetails)
for each error in the schema. | PydanticCustomError [¶](#pydantic_core.PydanticCustomError "Permanent link") ----------------------------------------------------------------------------- `PydanticCustomError( error_type: LiteralString, message_template: LiteralString, context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, )` Bases: `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` A custom exception providing flexible error handling for Pydantic validators. You can raise this error in custom validators when you'd like flexibility in regards to the error type, message, and context. Example `from pydantic_core import PydanticCustomError def custom_validator(v) -> None: if v <= 10: raise PydanticCustomError('custom_value_error', 'Value must be greater than {value}', {'value': 10, 'extra_context': 'extra_data'}) return v` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `error_type` | `LiteralString` | The error type. | _required_ | | `message_template` | `LiteralString` | The message template. | _required_ | | `context` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | The data to inject into the message template. | `None` | ### context `property` [¶](#pydantic_core.PydanticCustomError.context "Permanent link") `context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None` Values which are required to render the error message, and could hence be useful in passing error data forward. ### type `property` [¶](#pydantic_core.PydanticCustomError.type "Permanent link") `type: [str](https://docs.python.org/3/library/stdtypes.html#str)` The error type associated with the error. For consistency with Pydantic, this is typically a snake\_case string. ### message\_template `property` [¶](#pydantic_core.PydanticCustomError.message_template "Permanent link") `message_template: [str](https://docs.python.org/3/library/stdtypes.html#str)` The message template associated with the error. This is a string that can be formatted with context variables in `{curly_braces}`. ### message [¶](#pydantic_core.PydanticCustomError.message "Permanent link") `message() -> [str](https://docs.python.org/3/library/stdtypes.html#str)` The formatted message associated with the error. This presents as the message template with context variables appropriately injected. PydanticKnownError [¶](#pydantic_core.PydanticKnownError "Permanent link") --------------------------------------------------------------------------- `PydanticKnownError( error_type: ErrorType, context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, )` Bases: `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` A helper class for raising exceptions that mimic Pydantic's built-in exceptions, with more flexibility in regards to context. Unlike [`PydanticCustomError`](#pydantic_core.PydanticCustomError) , the `error_type` argument must be a known `ErrorType`. Example `from pydantic_core import PydanticKnownError def custom_validator(v) -> None: if v <= 10: raise PydanticKnownError(error_type='greater_than', context={'gt': 10}) return v` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `error_type` | `ErrorType` | The error type. | _required_ | | `context` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | The data to inject into the message template. | `None` | ### context `property` [¶](#pydantic_core.PydanticKnownError.context "Permanent link") `context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None` Values which are required to render the error message, and could hence be useful in passing error data forward. ### type `property` [¶](#pydantic_core.PydanticKnownError.type "Permanent link") `type: ErrorType` The type of the error. ### message\_template `property` [¶](#pydantic_core.PydanticKnownError.message_template "Permanent link") `message_template: [str](https://docs.python.org/3/library/stdtypes.html#str)` The message template associated with the provided error type. This is a string that can be formatted with context variables in `{curly_braces}`. ### message [¶](#pydantic_core.PydanticKnownError.message "Permanent link") `message() -> [str](https://docs.python.org/3/library/stdtypes.html#str)` The formatted message associated with the error. This presents as the message template with context variables appropriately injected. PydanticOmit [¶](#pydantic_core.PydanticOmit "Permanent link") --------------------------------------------------------------- Bases: `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` An exception to signal that a field should be omitted from a generated result. This could span from omitting a field from a JSON Schema to omitting a field from a serialized result. Upcoming: more robust support for using PydanticOmit in custom serializers is still in development. Right now, this is primarily used in the JSON Schema generation process. Example `from typing import Callable from pydantic_core import PydanticOmit from pydantic import BaseModel from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue class MyGenerateJsonSchema(GenerateJsonSchema): def handle_invalid_for_json_schema(self, schema, error_info) -> JsonSchemaValue: raise PydanticOmit class Predicate(BaseModel): name: str = 'no-op' func: Callable = lambda x: x instance_example = Predicate() validation_schema = instance_example.model_json_schema(schema_generator=MyGenerateJsonSchema, mode='validation') print(validation_schema) ''' {'properties': {'name': {'default': 'no-op', 'title': 'Name', 'type': 'string'}}, 'title': 'Predicate', 'type': 'object'} '''` For a more in depth example / explanation, see the [customizing JSON schema](../../concepts/json_schema/#customizing-the-json-schema-generation-process) docs. PydanticUseDefault [¶](#pydantic_core.PydanticUseDefault "Permanent link") --------------------------------------------------------------------------- Bases: `[Exception](https://docs.python.org/3/library/exceptions.html#Exception) ` An exception to signal that standard validation either failed or should be skipped, and the default value should be used instead. This warning can be raised in custom valiation functions to redirect the flow of validation. Example `from pydantic_core import PydanticUseDefault from datetime import datetime from pydantic import BaseModel, field_validator class Event(BaseModel): name: str = 'meeting' time: datetime @field_validator('name', mode='plain') def name_must_be_present(cls, v) -> str: if not v or not isinstance(v, str): raise PydanticUseDefault() return v event1 = Event(name='party', time=datetime(2024, 1, 1, 12, 0, 0)) print(repr(event1)) # > Event(name='party', time=datetime.datetime(2024, 1, 1, 12, 0)) event2 = Event(time=datetime(2024, 1, 1, 12, 0, 0)) print(repr(event2)) # > Event(name='meeting', time=datetime.datetime(2024, 1, 1, 12, 0))` For an additional example, see the [validating partial json data](../../concepts/json/#partial-json-parsing) section of the Pydantic documentation. PydanticSerializationError [¶](#pydantic_core.PydanticSerializationError "Permanent link") ------------------------------------------------------------------------------------------- `PydanticSerializationError(message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` An error raised when an issue occurs during serialization. In custom serializers, this error can be used to indicate that serialization has failed. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `message` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The message associated with the error. | _required_ | PydanticSerializationUnexpectedValue [¶](#pydantic_core.PydanticSerializationUnexpectedValue "Permanent link") --------------------------------------------------------------------------------------------------------------- `PydanticSerializationUnexpectedValue(message: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` An error raised when an unexpected value is encountered during serialization. This error is often caught and coerced into a warning, as `pydantic-core` generally makes a best attempt at serializing values, in contrast with validation where errors are eagerly raised. Example ``from pydantic import BaseModel, field_serializer from pydantic_core import PydanticSerializationUnexpectedValue class BasicPoint(BaseModel): x: int y: int @field_serializer('*') def serialize(self, v): if not isinstance(v, int): raise PydanticSerializationUnexpectedValue(f'Expected type `int`, got {type(v)} with value {v}') return v point = BasicPoint(x=1, y=2) # some sort of mutation point.x = 'a' print(point.model_dump()) ''' UserWarning: Pydantic serializer warnings: PydanticSerializationUnexpectedValue(Expected type `int`, got with value a) return self.__pydantic_serializer__.to_python( {'x': 'a', 'y': 2} '''`` This is often used internally in `pydantic-core` when unexpected types are encountered during serialization, but it can also be used by users in custom serializers, as seen above. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `message` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The message associated with the unexpected value. | _required_ | Url [¶](#pydantic_core.Url "Permanent link") --------------------------------------------- `Url(url: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `SupportsAllComparisons` A URL type, internal logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed by Mozilla. MultiHostUrl [¶](#pydantic_core.MultiHostUrl "Permanent link") --------------------------------------------------------------- `MultiHostUrl(url: [str](https://docs.python.org/3/library/stdtypes.html#str) )` Bases: `SupportsAllComparisons` A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. `https://foo.com,bar.com/path`. Internal URL logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed by Mozilla. MultiHostHost [¶](#pydantic_core.MultiHostHost "Permanent link") ----------------------------------------------------------------- Bases: `[TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict "typing.TypedDict") ` A host part of a multi-host URL. ### username `instance-attribute` [¶](#pydantic_core.MultiHostHost.username "Permanent link") `username: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The username part of this host, or `None`. ### password `instance-attribute` [¶](#pydantic_core.MultiHostHost.password "Permanent link") `password: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The password part of this host, or `None`. ### host `instance-attribute` [¶](#pydantic_core.MultiHostHost.host "Permanent link") `host: [str](https://docs.python.org/3/library/stdtypes.html#str) | None` The host part of this host, or `None`. ### port `instance-attribute` [¶](#pydantic_core.MultiHostHost.port "Permanent link") `port: [int](https://docs.python.org/3/library/functions.html#int) | None` The port part of this host, or `None`. ArgsKwargs [¶](#pydantic_core.ArgsKwargs "Permanent link") ----------------------------------------------------------- `ArgsKwargs( args: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ...], kwargs: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, )` A construct used to store arguments and keyword arguments for a function call. This data structure is generally used to store information for core schemas associated with functions (like in an arguments schema). This data structure is also currently used for some validation against dataclasses. Example `from pydantic.dataclasses import dataclass from pydantic import model_validator @dataclass class Model: a: int b: int @model_validator(mode="before") @classmethod def no_op_validator(cls, values): print(values) return values Model(1, b=2) #> ArgsKwargs((1,), {"b": 2}) Model(1, 2) #> ArgsKwargs((1, 2), {}) Model(a=1, b=2) #> ArgsKwargs((), {"a": 1, "b": 2})` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `args` | `[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ...]` | The arguments (inherently ordered) for a function call. | _required_ | | `kwargs` | `[dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | The keyword arguments for a function call | `None` | ### args `property` [¶](#pydantic_core.ArgsKwargs.args "Permanent link") `args: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ...]` The arguments (inherently ordered) for a function call. ### kwargs `property` [¶](#pydantic_core.ArgsKwargs.kwargs "Permanent link") `kwargs: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None` The keyword arguments for a function call. Some [¶](#pydantic_core.Some "Permanent link") ----------------------------------------------- Bases: `[Generic](https://docs.python.org/3/library/typing.html#typing.Generic "typing.Generic") [_T]` Similar to Rust's [`Option::Some`](https://doc.rust-lang.org/std/option/enum.Option.html) type, this identifies a value as being present, and provides a way to access it. Generally used in a union with `None` to different between "some value which could be None" and no value. ### value `property` [¶](#pydantic_core.Some.value "Permanent link") `value: _T` Returns the value wrapped by `Some`. TzInfo [¶](#pydantic_core.TzInfo "Permanent link") --------------------------------------------------- Bases: `[tzinfo](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") ` An `pydantic-core` implementation of the abstract [`datetime.tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) class. ### tzname [¶](#pydantic_core.TzInfo.tzname "Permanent link") `tzname(dt: [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") | None) -> [str](https://docs.python.org/3/library/stdtypes.html#str) | None` Return the time zone name corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) object _dt_, as a string. For more info, see [`tzinfo.tzname`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo.tzname) . ### utcoffset [¶](#pydantic_core.TzInfo.utcoffset "Permanent link") `utcoffset(dt: [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") | None) -> [timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta "datetime.timedelta") | None` Return offset of local time from UTC, as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object that is positive east of UTC. If local time is west of UTC, this should be negative. More info can be found at [`tzinfo.utcoffset`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo.utcoffset) . ### dst [¶](#pydantic_core.TzInfo.dst "Permanent link") `dst(dt: [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") | None) -> [timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta "datetime.timedelta") | None` Return the daylight saving time (DST) adjustment, as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object or `None` if DST information isn’t known. More info can be found at[`tzinfo.dst`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo.dst) . ### fromutc [¶](#pydantic_core.TzInfo.fromutc "Permanent link") `fromutc(dt: [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") ) -> [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime")` Adjust the date and time data associated datetime object _dt_, returning an equivalent datetime in self’s local time. More info can be found at [`tzinfo.fromutc`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo.fromutc) . ErrorTypeInfo [¶](#pydantic_core.ErrorTypeInfo "Permanent link") ----------------------------------------------------------------- Bases: `[TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict "typing.TypedDict") ` Gives information about errors. ### type `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.type "Permanent link") `type: ErrorType` The type of error that occurred, this should a "slug" identifier that changes rarely or never. ### message\_template\_python `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.message_template_python "Permanent link") `message_template_python: [str](https://docs.python.org/3/library/stdtypes.html#str)` String template to render a human readable error message from using context, when the input is Python. ### example\_message\_python `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.example_message_python "Permanent link") `example_message_python: [str](https://docs.python.org/3/library/stdtypes.html#str)` Example of a human readable error message, when the input is Python. ### message\_template\_json `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.message_template_json "Permanent link") `message_template_json: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` String template to render a human readable error message from using context, when the input is JSON data. ### example\_message\_json `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.example_message_json "Permanent link") `example_message_json: [NotRequired](https://docs.python.org/3/library/typing.html#typing.NotRequired "typing.NotRequired") [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` Example of a human readable error message, when the input is JSON data. ### example\_context `instance-attribute` [¶](#pydantic_core.ErrorTypeInfo.example_context "Permanent link") `example_context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None` Example of context values. to\_json [¶](#pydantic_core.to_json "Permanent link") ------------------------------------------------------ `to_json( value: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, indent: [int](https://docs.python.org/3/library/functions.html#int) | None = None, include: _IncEx | None = None, exclude: _IncEx | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) = True, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, timedelta_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["iso8601", "float"] = "iso8601", bytes_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["utf8", "base64", "hex"] = "utf8", inf_nan_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [ "null", "constants", "strings" ] = "constants", serialize_unknown: [bool](https://docs.python.org/3/library/functions.html#bool) = False, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None ) -> [bytes](https://docs.python.org/3/library/stdtypes.html#bytes)` Serialize a Python object to JSON including transforming and filtering data. This is effectively a standalone version of [`SchemaSerializer.to_json`](#pydantic_core.SchemaSerializer.to_json) . Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The Python object to serialize. | _required_ | | `indent` | `[int](https://docs.python.org/3/library/functions.html#int) \| None` | If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided. | `None` | | `include` | `_IncEx \| None` | A set of fields to include, if `None` all fields are included. | `None` | | `exclude` | `_IncEx \| None` | A set of fields to exclude, if `None` no fields are excluded. | `None` | | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to use the alias names of fields. | `True` | | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` | | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to enable serialization and validation round-trip support. | `False` | | `timedelta_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['iso8601', 'float']` | How to serialize `timedelta` objects, either `'iso8601'` or `'float'`. | `'iso8601'` | | `bytes_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['utf8', 'base64', 'hex']` | How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`. | `'utf8'` | | `inf_nan_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['null', 'constants', 'strings']` | How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`. | `'constants'` | | `serialize_unknown` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Attempt to serialize unknown types, `str(value)` will be used, if that fails `""` will be used. | `False` | | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered, if `None` a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
error is raised. | `None` | | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` | | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for serialization, this is passed to functional serializers as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo.context)
. | `None` | Raises: | Type | Description | | --- | --- | | `[PydanticSerializationError](#pydantic_core.PydanticSerializationError "pydantic_core._pydantic_core.PydanticSerializationError") ` | If serialization fails and no `fallback` function is provided. | Returns: | Type | Description | | --- | --- | | `[bytes](https://docs.python.org/3/library/stdtypes.html#bytes) ` | JSON bytes. | from\_json [¶](#pydantic_core.from_json "Permanent link") ---------------------------------------------------------- `from_json( data: [str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) , *, allow_inf_nan: [bool](https://docs.python.org/3/library/functions.html#bool) = True, cache_strings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["all", "keys", "none"] ) = True, allow_partial: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["off", "on", "trailing-strings"] ) = False ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Deserialize JSON data to a Python object. This is effectively a faster version of `json.loads()`, with some extra functionality. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `data` | `[str](https://docs.python.org/3/library/stdtypes.html#str) \| [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) \| [bytearray](https://docs.python.org/3/library/stdtypes.html#bytearray) ` | The JSON data to deserialize. | _required_ | | `allow_inf_nan` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to allow `Infinity`, `-Infinity` and `NaN` values as `json.loads()` does by default. | `True` | | `cache_strings` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['all', 'keys', 'none']` | Whether to cache strings to avoid constructing new Python objects, this should have a significant impact on performance while increasing memory usage slightly, `all/True` means cache all strings, `keys` means cache only dict keys, `none/False` means no caching. | `True` | | `allow_partial` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['off', 'on', 'trailing-strings']` | Whether to allow partial deserialization, if `True` JSON data is returned if the end of the input is reached before the full object is deserialized, e.g. `["aa", "bb", "c` would return `['aa', 'bb']`. `'trailing-strings'` means any final unfinished JSON string is included in the result. | `False` |\ \ Raises:\ \ | Type | Description |\ | --- | --- |\ | `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` | If deserialization fails. |\ \ Returns:\ \ | Type | Description |\ | --- | --- |\ | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The deserialized Python object. |\ \ to\_jsonable\_python [¶](#pydantic_core.to_jsonable_python "Permanent link")\ \ -----------------------------------------------------------------------------\ \ `to_jsonable_python( value: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , *, include: _IncEx | None = None, exclude: _IncEx | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) = True, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, timedelta_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["iso8601", "float"] = "iso8601", bytes_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["utf8", "base64", "hex"] = "utf8", inf_nan_mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") [ "null", "constants", "strings" ] = "constants", serialize_unknown: [bool](https://docs.python.org/3/library/functions.html#bool) = False, fallback: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False, context: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") | None = None ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")`\ \ Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.\ \ This is effectively a standalone version of [`SchemaSerializer.to_python(mode='json')`](#pydantic_core.SchemaSerializer.to_python)\ .\ \ Parameters:\ \ | Name | Type | Description | Default |\ | --- | --- | --- | --- |\ | `value` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The Python object to serialize. | _required_ |\ | `include` | `_IncEx \| None` | A set of fields to include, if `None` all fields are included. | `None` |\ | `exclude` | `_IncEx \| None` | A set of fields to exclude, if `None` no fields are excluded. | `None` |\ | `by_alias` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to use the alias names of fields. | `True` |\ | `exclude_none` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to exclude fields that have a value of `None`. | `False` |\ | `round_trip` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to enable serialization and validation round-trip support. | `False` |\ | `timedelta_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['iso8601', 'float']` | How to serialize `timedelta` objects, either `'iso8601'` or `'float'`. | `'iso8601'` |\ | `bytes_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['utf8', 'base64', 'hex']` | How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`. | `'utf8'` |\ | `inf_nan_mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['null', 'constants', 'strings']` | How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`. | `'constants'` |\ | `serialize_unknown` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Attempt to serialize unknown types, `str(value)` will be used, if that fails `""` will be used. | `False` |\ | `fallback` | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] \| None` | A function to call when an unknown value is encountered, if `None` a [`PydanticSerializationError`](#pydantic_core.PydanticSerializationError)
error is raised. | `None` |\ | `serialize_as_any` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | Whether to serialize fields with duck-typing serialization behavior. | `False` |\ | `context` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") \| None` | The context to use for serialization, this is passed to functional serializers as [`info.context`](../pydantic_core_schema/#pydantic_core.core_schema.SerializationInfo.context)
. | `None` |\ \ Raises:\ \ | Type | Description |\ | --- | --- |\ | `[PydanticSerializationError](#pydantic_core.PydanticSerializationError "pydantic_core._pydantic_core.PydanticSerializationError") ` | If serialization fails and no `fallback` function is provided. |\ \ Returns:\ \ | Type | Description |\ | --- | --- |\ | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The serialized Python object. |\ \ Was this page helpful?\ \ Thanks for your feedback!\ \ Thanks for your feedback!\ \ Back to top --- # Functional Validators - Pydantic Functional Validators ===================== This module contains related classes and functions for validation. ModelAfterValidatorWithoutInfo `module-attribute` [¶](#pydantic.functional_validators.ModelAfterValidatorWithoutInfo "Permanent link") --------------------------------------------------------------------------------------------------------------------------------------- `ModelAfterValidatorWithoutInfo = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelType], _ModelType ]` A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not have info argument. ModelAfterValidator `module-attribute` [¶](#pydantic.functional_validators.ModelAfterValidator "Permanent link") ----------------------------------------------------------------------------------------------------------------- `ModelAfterValidator = [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_ModelType, [ValidationInfo](../pydantic_core_schema/#pydantic_core.core_schema.ValidationInfo "pydantic_core.core_schema.ValidationInfo") ], _ModelType ]` A `@model_validator` decorated function signature. This is used when `mode='after'`. AfterValidator `dataclass` [¶](#pydantic.functional_validators.AfterValidator "Permanent link") ------------------------------------------------------------------------------------------------ `AfterValidator( func: ( NoInfoValidatorFunction | WithInfoValidatorFunction ), )` Usage Documentation [field _after_ validators](../../concepts/validators/#field-after-validator) A metadata class that indicates that a validation should be applied **after** the inner validation logic. Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `NoInfoValidatorFunction \| WithInfoValidatorFunction` | The validator function. | Example `from typing import Annotated from pydantic import AfterValidator, BaseModel, ValidationError MyInt = Annotated[int, AfterValidator(lambda v: v + 1)] class Model(BaseModel): a: MyInt print(Model(a=1).a) #> 2 try: Model(a='a') except ValidationError as e: print(e.json(indent=2)) ''' [ { "type": "int_parsing", "loc": [ "a" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", "url": "https://errors.pydantic.dev/2/v/int_parsing" } ] '''` BeforeValidator `dataclass` [¶](#pydantic.functional_validators.BeforeValidator "Permanent link") -------------------------------------------------------------------------------------------------- `BeforeValidator( func: ( NoInfoValidatorFunction | WithInfoValidatorFunction ), json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, )` Usage Documentation [field _before_ validators](../../concepts/validators/#field-before-validator) A metadata class that indicates that a validation should be applied **before** the inner validation logic. Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `NoInfoValidatorFunction \| WithInfoValidatorFunction` | The validator function. | | `json_schema_input_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode). | Example `from typing import Annotated from pydantic import BaseModel, BeforeValidator MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)] class Model(BaseModel): a: MyInt print(Model(a=1).a) #> 2 try: Model(a='a') except TypeError as e: print(e) #> can only concatenate str (not "int") to str` PlainValidator `dataclass` [¶](#pydantic.functional_validators.PlainValidator "Permanent link") ------------------------------------------------------------------------------------------------ `PlainValidator( func: ( NoInfoValidatorFunction | WithInfoValidatorFunction ), json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , )` Usage Documentation [field _plain_ validators](../../concepts/validators/#field-plain-validator) A metadata class that indicates that a validation should be applied **instead** of the inner validation logic. Note Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`. You can now use the `json_schema_input_type` argument to specify the input type of the function to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details. Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `NoInfoValidatorFunction \| WithInfoValidatorFunction` | The validator function. | | `json_schema_input_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode). If not provided, will default to `Any`. | Example `from typing import Annotated, Union from pydantic import BaseModel, PlainValidator MyInt = Annotated[ int, PlainValidator( lambda v: int(v) + 1, json_schema_input_type=Union[str, int] # (1)! ), ] class Model(BaseModel): a: MyInt print(Model(a='1').a) #> 2 print(Model(a=1).a) #> 2` 1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema generator that in validation mode, the input type for the `a` field can be either a `str` or an `int`. WrapValidator `dataclass` [¶](#pydantic.functional_validators.WrapValidator "Permanent link") ---------------------------------------------------------------------------------------------- `WrapValidator( func: ( NoInfoWrapValidatorFunction | WithInfoWrapValidatorFunction ), json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, )` Usage Documentation [field _wrap_ validators](../../concepts/validators/#field-wrap-validator) A metadata class that indicates that a validation should be applied **around** the inner validation logic. Attributes: | Name | Type | Description | | --- | --- | --- | | `func` | `NoInfoWrapValidatorFunction \| WithInfoWrapValidatorFunction` | The validator function. | | `json_schema_input_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode). | `from datetime import datetime from typing import Annotated from pydantic import BaseModel, ValidationError, WrapValidator def validate_timestamp(v, handler): if v == 'now': # we don't want to bother with further validation, just return the new value return datetime.now() try: return handler(v) except ValidationError: # validation failed, in this case we want to return a default value return datetime(2000, 1, 1) MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)] class Model(BaseModel): a: MyTimestamp print(Model(a='now').a) #> 2032-01-02 03:04:05.000006 print(Model(a='invalid').a) #> 2000-01-01 00:00:00` ModelWrapValidatorHandler [¶](#pydantic.functional_validators.ModelWrapValidatorHandler "Permanent link") ---------------------------------------------------------------------------------------------------------- Bases: `ValidatorFunctionWrapHandler`, `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") [_ModelTypeCo]` `@model_validator` decorated function handler argument type. This is used when `mode='wrap'`. ModelWrapValidatorWithoutInfo [¶](#pydantic.functional_validators.ModelWrapValidatorWithoutInfo "Permanent link") ------------------------------------------------------------------------------------------------------------------ Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") [_ModelType]` A `@model_validator` decorated function signature. This is used when `mode='wrap'` and the function does not have info argument. ModelWrapValidator [¶](#pydantic.functional_validators.ModelWrapValidator "Permanent link") -------------------------------------------------------------------------------------------- Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") [_ModelType]` A `@model_validator` decorated function signature. This is used when `mode='wrap'`. FreeModelBeforeValidatorWithoutInfo [¶](#pydantic.functional_validators.FreeModelBeforeValidatorWithoutInfo "Permanent link") ------------------------------------------------------------------------------------------------------------------------------ Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") ` A `@model_validator` decorated function signature. This is used when `mode='before'` and the function does not have info argument. ModelBeforeValidatorWithoutInfo [¶](#pydantic.functional_validators.ModelBeforeValidatorWithoutInfo "Permanent link") ---------------------------------------------------------------------------------------------------------------------- Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") ` A `@model_validator` decorated function signature. This is used when `mode='before'` and the function does not have info argument. FreeModelBeforeValidator [¶](#pydantic.functional_validators.FreeModelBeforeValidator "Permanent link") -------------------------------------------------------------------------------------------------------- Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") ` A `@model_validator` decorated function signature. This is used when `mode='before'`. ModelBeforeValidator [¶](#pydantic.functional_validators.ModelBeforeValidator "Permanent link") ------------------------------------------------------------------------------------------------ Bases: `[Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol "typing.Protocol") ` A `@model_validator` decorated function signature. This is used when `mode='before'`. InstanceOf `dataclass` [¶](#pydantic.functional_validators.InstanceOf "Permanent link") ---------------------------------------------------------------------------------------- `InstanceOf()` Generic type for annotating a type that is an instance of a given class. Example `from pydantic import BaseModel, InstanceOf class Foo: ... class Bar(BaseModel): foo: InstanceOf[Foo] Bar(foo=Foo()) try: Bar(foo=42) except ValidationError as e: print(e) """ [ │ { │ │ 'type': 'is_instance_of', │ │ 'loc': ('foo',), │ │ 'msg': 'Input should be an instance of Foo', │ │ 'input': 42, │ │ 'ctx': {'class': 'Foo'}, │ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of' │ } ] """` SkipValidation `dataclass` [¶](#pydantic.functional_validators.SkipValidation "Permanent link") ------------------------------------------------------------------------------------------------ `SkipValidation()` If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`. This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes, and know that it is safe to skip validation for one or more of the fields. Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations may not have the expected effects. Therefore, when used, this annotation should generally be the final annotation applied to a type. field\_validator [¶](#pydantic.functional_validators.field_validator "Permanent link") --------------------------------------------------------------------------------------- `field_validator( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["wrap"], check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = ..., json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ..., ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[_V2WrapValidatorType], _V2WrapValidatorType]` `field_validator( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["before", "plain"], check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = ..., json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = ..., ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType, ]` `field_validator( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["after"] = ..., check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = ..., ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType, ]` `field_validator( field: [str](https://docs.python.org/3/library/stdtypes.html#str) , /, *fields: [str](https://docs.python.org/3/library/stdtypes.html#str) , mode: FieldValidatorModes = "after", check_fields: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, json_schema_input_type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = PydanticUndefined, ) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` Usage Documentation [field validators](../../concepts/validators/#field-validators) Decorate methods on the class indicating that they should be used to validate fields. Example usage: `from typing import Any from pydantic import ( BaseModel, ValidationError, field_validator, ) class Model(BaseModel): a: str @field_validator('a') @classmethod def ensure_foobar(cls, v: Any): if 'foobar' not in v: raise ValueError('"foobar" not found in a') return v print(repr(Model(a='this is foobar good'))) #> Model(a='this is foobar good') try: Model(a='snap') except ValidationError as exc_info: print(exc_info) ''' 1 validation error for Model a Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str] '''` For more in depth examples, see [Field Validators](../../concepts/validators/#field-validators) . Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `field` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The first field the `field_validator` should be called on; this is separate from `fields` to ensure an error is raised if you don't pass at least one. | _required_ | | `*fields` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | Additional field(s) the `field_validator` should be called on. | `()` | | `mode` | `FieldValidatorModes` | Specifies whether to validate the fields before or after validation. | `'after'` | | `check_fields` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to check that the fields actually exist on the model. | `None` | | `json_schema_input_type` | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode) and can only specified when `mode` is either `'before'`, `'plain'` or `'wrap'`. | `PydanticUndefined` | Returns: | Type | Description | | --- | --- | | `[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [[[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ], [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ]` | A decorator that can be used to decorate a function to be used as a field\_validator. | Raises: | Type | Description | | --- | --- | | `[PydanticUserError](../errors/#pydantic.errors.PydanticUserError "pydantic.errors.PydanticUserError") ` | * If `@field_validator` is used bare (with no fields).
* If the args passed to `@field_validator` as fields are not strings.
* If `@field_validator` applied to instance methods. | Source code in `pydantic/functional_validators.py` | | | | --- | --- | | 407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515 | ``def field_validator( field: str, /, *fields: str, mode: FieldValidatorModes = 'after', check_fields: bool \| None = None, json_schema_input_type: Any = PydanticUndefined, ) -> Callable[[Any], Any]: """!!! abstract "Usage Documentation" [field validators](../concepts/validators.md#field-validators) Decorate methods on the class indicating that they should be used to validate fields. Example usage: ```python from typing import Any from pydantic import ( BaseModel, ValidationError, field_validator, ) class Model(BaseModel): a: str @field_validator('a') @classmethod def ensure_foobar(cls, v: Any): if 'foobar' not in v: raise ValueError('"foobar" not found in a') return v print(repr(Model(a='this is foobar good'))) #> Model(a='this is foobar good') try: Model(a='snap') except ValidationError as exc_info: print(exc_info) ''' 1 validation error for Model a Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str] ''' ``` For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators). Args: field: The first field the `field_validator` should be called on; this is separate from `fields` to ensure an error is raised if you don't pass at least one. *fields: Additional field(s) the `field_validator` should be called on. mode: Specifies whether to validate the fields before or after validation. check_fields: Whether to check that the fields actually exist on the model. json_schema_input_type: The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode) and can only specified when `mode` is either `'before'`, `'plain'` or `'wrap'`. Returns: A decorator that can be used to decorate a function to be used as a field_validator. Raises: PydanticUserError: - If `@field_validator` is used bare (with no fields). - If the args passed to `@field_validator` as fields are not strings. - If `@field_validator` applied to instance methods. """ if isinstance(field, FunctionType): raise PydanticUserError( '`@field_validator` should be used with fields and keyword arguments, not bare. ' "E.g. usage should be `@validator('', ...)`", code='validator-no-fields', ) if mode not in ('before', 'plain', 'wrap') and json_schema_input_type is not PydanticUndefined: raise PydanticUserError( f"`json_schema_input_type` can't be used when mode is set to {mode!r}", code='validator-input-type', ) if json_schema_input_type is PydanticUndefined and mode == 'plain': json_schema_input_type = Any fields = field, *fields if not all(isinstance(field, str) for field in fields): raise PydanticUserError( '`@field_validator` fields should be passed as separate string args. ' "E.g. usage should be `@validator('', '', ...)`", code='validator-invalid-fields', ) def dec( f: Callable[..., Any] \| staticmethod[Any, Any] \| classmethod[Any, Any, Any], ) -> _decorators.PydanticDescriptorProxy[Any]: if _decorators.is_instance_method_from_sig(f): raise PydanticUserError( '`@field_validator` cannot be applied to instance methods', code='validator-instance-method' ) # auto apply the @classmethod decorator f = _decorators.ensure_classmethod_based_on_signature(f) dec_info = _decorators.FieldValidatorDecoratorInfo( fields=fields, mode=mode, check_fields=check_fields, json_schema_input_type=json_schema_input_type ) return _decorators.PydanticDescriptorProxy(f, dec_info) return dec`` | model\_validator [¶](#pydantic.functional_validators.model_validator "Permanent link") --------------------------------------------------------------------------------------- `model_validator(*, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["wrap"]) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_AnyModelWrapValidator[_ModelType]], PydanticDescriptorProxy[ModelValidatorDecoratorInfo], ]` `model_validator(*, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["before"]) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_AnyModelBeforeValidator], PydanticDescriptorProxy[ModelValidatorDecoratorInfo], ]` `model_validator(*, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["after"]) -> [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "typing.Callable") [ [_AnyModelAfterValidator[_ModelType]], PydanticDescriptorProxy[ModelValidatorDecoratorInfo], ]` `model_validator( *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["wrap", "before", "after"] ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` Usage Documentation [Model Validators](../../concepts/validators/#model-validators) Decorate model methods for validation purposes. Example usage: `from typing_extensions import Self from pydantic import BaseModel, ValidationError, model_validator class Square(BaseModel): width: float height: float @model_validator(mode='after') def verify_square(self) -> Self: if self.width != self.height: raise ValueError('width and height do not match') return self s = Square(width=1, height=1) print(repr(s)) #> Square(width=1.0, height=1.0) try: Square(width=1, height=2) except ValidationError as e: print(e) ''' 1 validation error for Square Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict] '''` For more in depth examples, see [Model Validators](../../concepts/validators/#model-validators) . Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `mode` | `[Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['wrap', 'before', 'after']` | A required string literal that specifies the validation mode. It can be one of the following: 'wrap', 'before', or 'after'. | _required_ | Returns: | Type | Description | | --- | --- | | `[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ` | A decorator that can be used to decorate a function to be used as a model validator. | Source code in `pydantic/functional_validators.py` | | | | --- | --- | | 669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724 | `def model_validator( *, mode: Literal['wrap', 'before', 'after'], ) -> Any: """!!! abstract "Usage Documentation" [Model Validators](../concepts/validators.md#model-validators) Decorate model methods for validation purposes. Example usage: ```python from typing_extensions import Self from pydantic import BaseModel, ValidationError, model_validator class Square(BaseModel): width: float height: float @model_validator(mode='after') def verify_square(self) -> Self: if self.width != self.height: raise ValueError('width and height do not match') return self s = Square(width=1, height=1) print(repr(s)) #> Square(width=1.0, height=1.0) try: Square(width=1, height=2) except ValidationError as e: print(e) ''' 1 validation error for Square Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict] ''' ``` For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators). Args: mode: A required string literal that specifies the validation mode. It can be one of the following: 'wrap', 'before', or 'after'. Returns: A decorator that can be used to decorate a function to be used as a model validator. """ def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]: # auto apply the @classmethod decorator f = _decorators.ensure_classmethod_based_on_signature(f) dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode) return _decorators.PydanticDescriptorProxy(f, dec_info) return dec` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # ISBN - Pydantic ISBN ==== The `pydantic_extra_types.isbn` module provides functionality to recieve and validate ISBN. ISBN (International Standard Book Number) is a numeric commercial book identifier which is intended to be unique. This module provides a ISBN type for Pydantic models. ISBN [¶](#pydantic_extra_types.isbn.ISBN "Permanent link") ----------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` Represents a ISBN and provides methods for conversion, validation, and serialization. `from pydantic import BaseModel from pydantic_extra_types.isbn import ISBN class Book(BaseModel): isbn: ISBN book = Book(isbn="8537809667") print(book) #> isbn='9788537809662'` ### validate\_isbn\_format `staticmethod` [¶](#pydantic_extra_types.isbn.ISBN.validate_isbn_format "Permanent link") `validate_isbn_format(value: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> None` Validate a ISBN format from the provided str value. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The str value representing the ISBN in 10 or 13 digits. | _required_ | Raises: | Type | Description | | --- | --- | | `[PydanticCustomError](../pydantic_core/#pydantic_core.PydanticCustomError "pydantic_core.PydanticCustomError") ` | If the ISBN is not valid. | Source code in `pydantic_extra_types/isbn.py` | | | | --- | --- | | 104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 | `@staticmethod def validate_isbn_format(value: str) -> None: """Validate a ISBN format from the provided str value. Args: value: The str value representing the ISBN in 10 or 13 digits. Raises: PydanticCustomError: If the ISBN is not valid. """ isbn_length = len(value) if isbn_length not in (10, 13): raise PydanticCustomError('isbn_length', f'Length for ISBN must be 10 or 13 digits, not {isbn_length}') if isbn_length == 10: if not value[:-1].isdigit() or ((value[-1] != 'X') and (not value[-1].isdigit())): raise PydanticCustomError('isbn10_invalid_characters', 'First 9 digits of ISBN-10 must be integers') if isbn10_digit_calc(value) != value[-1]: raise PydanticCustomError('isbn_invalid_digit_check_isbn10', 'Provided digit is invalid for given ISBN') if isbn_length == 13: if not value.isdigit(): raise PydanticCustomError('isbn13_invalid_characters', 'All digits of ISBN-13 must be integers') if value[:3] not in ('978', '979'): raise PydanticCustomError( 'isbn_invalid_early_characters', 'The first 3 digits of ISBN-13 must be 978 or 979' ) if isbn13_digit_calc(value) != value[-1]: raise PydanticCustomError('isbn_invalid_digit_check_isbn13', 'Provided digit is invalid for given ISBN')` | ### convert\_isbn10\_to\_isbn13 `staticmethod` [¶](#pydantic_extra_types.isbn.ISBN.convert_isbn10_to_isbn13 "Permanent link") `convert_isbn10_to_isbn13(value: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Convert an ISBN-10 to ISBN-13. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The ISBN-10 value to be converted. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The converted ISBN or the original value if no conversion is necessary. | Source code in `pydantic_extra_types/isbn.py` | | | | --- | --- | | 136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152 | `@staticmethod def convert_isbn10_to_isbn13(value: str) -> str: """Convert an ISBN-10 to ISBN-13. Args: value: The ISBN-10 value to be converted. Returns: The converted ISBN or the original value if no conversion is necessary. """ if len(value) == 10: base_isbn = f'978{value[:-1]}' isbn13_digit = isbn13_digit_calc(base_isbn) return ISBN(f'{base_isbn}{isbn13_digit}') return ISBN(value)` | isbn10\_digit\_calc [¶](#pydantic_extra_types.isbn.isbn10_digit_calc "Permanent link") --------------------------------------------------------------------------------------- `isbn10_digit_calc(isbn: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Calc a ISBN-10 last digit from the provided str value. More information of validation algorithm on [Wikipedia](https://en.wikipedia.org/wiki/ISBN#Check_digits) Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `isbn` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The str value representing the ISBN in 10 digits. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The calculated last digit of the ISBN-10 value. | Source code in `pydantic_extra_types/isbn.py` | | | | --- | --- | | 15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | `def isbn10_digit_calc(isbn: str) -> str: """Calc a ISBN-10 last digit from the provided str value. More information of validation algorithm on [Wikipedia](https://en.wikipedia.org/wiki/ISBN#Check_digits) Args: isbn: The str value representing the ISBN in 10 digits. Returns: The calculated last digit of the ISBN-10 value. """ total = sum(int(digit) * (10 - idx) for idx, digit in enumerate(isbn[:9])) for check_digit in range(1, 11): if (total + check_digit) % 11 == 0: valid_check_digit = 'X' if check_digit == 10 else str(check_digit) return valid_check_digit` | isbn13\_digit\_calc [¶](#pydantic_extra_types.isbn.isbn13_digit_calc "Permanent link") --------------------------------------------------------------------------------------- `isbn13_digit_calc(isbn: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Calc a ISBN-13 last digit from the provided str value. More information of validation algorithm on [Wikipedia](https://en.wikipedia.org/wiki/ISBN#Check_digits) Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `isbn` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The str value representing the ISBN in 13 digits. | _required_ | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The calculated last digit of the ISBN-13 value. | Source code in `pydantic_extra_types/isbn.py` | | | | --- | --- | | 33
34
35
36
37
38
39
40
41
42
43
44
45
46 | `def isbn13_digit_calc(isbn: str) -> str: """Calc a ISBN-13 last digit from the provided str value. More information of validation algorithm on [Wikipedia](https://en.wikipedia.org/wiki/ISBN#Check_digits) Args: isbn: The str value representing the ISBN in 13 digits. Returns: The calculated last digit of the ISBN-13 value. """ total = sum(int(digit) * (1 if idx % 2 == 0 else 3) for idx, digit in enumerate(isbn[:12])) check_digit = (10 - (total % 10)) % 10 return str(check_digit)` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Currency - Pydantic Currency ======== Currency definitions that are based on the [ISO4217](https://en.wikipedia.org/wiki/ISO_4217) . ISO4217 [¶](#pydantic_extra_types.currency_code.ISO4217 "Permanent link") -------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` ISO4217 parses Currency in the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) format. `from pydantic import BaseModel from pydantic_extra_types.currency_code import ISO4217 class Currency(BaseModel): alpha_3: ISO4217 currency = Currency(alpha_3='AED') print(currency) # > alpha_3='AED'` Currency [¶](#pydantic_extra_types.currency_code.Currency "Permanent link") ---------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` Currency parses currency subset of the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) format. It excludes bonds testing codes and precious metals. `from pydantic import BaseModel from pydantic_extra_types.currency_code import Currency class currency(BaseModel): alpha_3: Currency cur = currency(alpha_3='AED') print(cur) # > alpha_3='AED'` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Coordinate - Pydantic Coordinate ========== The `pydantic_extra_types.coordinate` module provides the [`Latitude`](#pydantic_extra_types.coordinate.Latitude) , [`Longitude`](#pydantic_extra_types.coordinate.Longitude) , and [`Coordinate`](#pydantic_extra_types.coordinate.Coordinate) data types. Latitude [¶](#pydantic_extra_types.coordinate.Latitude "Permanent link") ------------------------------------------------------------------------- Bases: `[float](https://docs.python.org/3/library/functions.html#float) ` Latitude value should be between -90 and 90, inclusive. `from pydantic import BaseModel from pydantic_extra_types.coordinate import Latitude class Location(BaseModel): latitude: Latitude location = Location(latitude=41.40338) print(location) #> latitude=41.40338` Longitude [¶](#pydantic_extra_types.coordinate.Longitude "Permanent link") --------------------------------------------------------------------------- Bases: `[float](https://docs.python.org/3/library/functions.html#float) ` Longitude value should be between -180 and 180, inclusive. `from pydantic import BaseModel from pydantic_extra_types.coordinate import Longitude class Location(BaseModel): longitude: Longitude location = Location(longitude=2.17403) print(location) #> longitude=2.17403` Coordinate `dataclass` [¶](#pydantic_extra_types.coordinate.Coordinate "Permanent link") ----------------------------------------------------------------------------------------- `Coordinate(latitude: [Latitude](#pydantic_extra_types.coordinate.Latitude "pydantic_extra_types.coordinate.Latitude") , longitude: [Longitude](#pydantic_extra_types.coordinate.Longitude "pydantic_extra_types.coordinate.Longitude") )` Bases: `Representation` Coordinate parses Latitude and Longitude. You can use the `Coordinate` data type for storing coordinates. Coordinates can be defined using one of the following formats: 1. Tuple: `(Latitude, Longitude)`. For example: `(41.40338, 2.17403)`. 2. `Coordinate` instance: `Coordinate(latitude=Latitude, longitude=Longitude)`. `from pydantic import BaseModel from pydantic_extra_types.coordinate import Coordinate class Location(BaseModel): coordinate: Coordinate location = Location(coordinate=(41.40338, 2.17403)) #> coordinate=Coordinate(latitude=41.40338, longitude=2.17403)` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Country - Pydantic Country ======= Country definitions that are based on the [ISO 3166](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes) . CountryAlpha2 [¶](#pydantic_extra_types.country.CountryAlpha2 "Permanent link") -------------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` CountryAlpha2 parses country codes in the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. `from pydantic import BaseModel from pydantic_extra_types.country import CountryAlpha2 class Product(BaseModel): made_in: CountryAlpha2 product = Product(made_in='ES') print(product) #> made_in='ES'` ### alpha3 `property` [¶](#pydantic_extra_types.country.CountryAlpha2.alpha3 "Permanent link") `alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. ### numeric\_code `property` [¶](#pydantic_extra_types.country.CountryAlpha2.numeric_code "Permanent link") `numeric_code: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 numeric](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format. ### short\_name `property` [¶](#pydantic_extra_types.country.CountryAlpha2.short_name "Permanent link") `short_name: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country short name. CountryAlpha3 [¶](#pydantic_extra_types.country.CountryAlpha3 "Permanent link") -------------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` CountryAlpha3 parses country codes in the [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. `from pydantic import BaseModel from pydantic_extra_types.country import CountryAlpha3 class Product(BaseModel): made_in: CountryAlpha3 product = Product(made_in="USA") print(product) #> made_in='USA'` ### alpha2 `property` [¶](#pydantic_extra_types.country.CountryAlpha3.alpha2 "Permanent link") `alpha2: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. ### numeric\_code `property` [¶](#pydantic_extra_types.country.CountryAlpha3.numeric_code "Permanent link") `numeric_code: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 numeric](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format. ### short\_name `property` [¶](#pydantic_extra_types.country.CountryAlpha3.short_name "Permanent link") `short_name: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country short name. CountryNumericCode [¶](#pydantic_extra_types.country.CountryNumericCode "Permanent link") ------------------------------------------------------------------------------------------ Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` CountryNumericCode parses country codes in the [ISO 3166-1 numeric](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format. `from pydantic import BaseModel from pydantic_extra_types.country import CountryNumericCode class Product(BaseModel): made_in: CountryNumericCode product = Product(made_in="840") print(product) #> made_in='840'` ### alpha2 `property` [¶](#pydantic_extra_types.country.CountryNumericCode.alpha2 "Permanent link") `alpha2: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. ### alpha3 `property` [¶](#pydantic_extra_types.country.CountryNumericCode.alpha3 "Permanent link") `alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. ### short\_name `property` [¶](#pydantic_extra_types.country.CountryNumericCode.short_name "Permanent link") `short_name: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country short name. CountryShortName [¶](#pydantic_extra_types.country.CountryShortName "Permanent link") -------------------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` CountryShortName parses country codes in the short name format. `from pydantic import BaseModel from pydantic_extra_types.country import CountryShortName class Product(BaseModel): made_in: CountryShortName product = Product(made_in="United States") print(product) #> made_in='United States'` ### alpha2 `property` [¶](#pydantic_extra_types.country.CountryShortName.alpha2 "Permanent link") `alpha2: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format. ### alpha3 `property` [¶](#pydantic_extra_types.country.CountryShortName.alpha3 "Permanent link") `alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) format. ### numeric\_code `property` [¶](#pydantic_extra_types.country.CountryShortName.numeric_code "Permanent link") `numeric_code: [str](https://docs.python.org/3/library/stdtypes.html#str)` The country code in the [ISO 3166-1 numeric](https://en.wikipedia.org/wiki/ISO_3166-1_numeric) format. Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Color - Pydantic Color ===== Color definitions are used as per the CSS3 [CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification. A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`. In these cases the _last_ color when sorted alphabetically takes preferences, eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua". RGBA [¶](#pydantic_extra_types.color.RGBA "Permanent link") ------------------------------------------------------------ `RGBA(r: [float](https://docs.python.org/3/library/functions.html#float) , g: [float](https://docs.python.org/3/library/functions.html#float) , b: [float](https://docs.python.org/3/library/functions.html#float) , alpha: [float](https://docs.python.org/3/library/functions.html#float) | None)` Internal use only as a representation of a color. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 35
36
37
38
39
40
41 | `def __init__(self, r: float, g: float, b: float, alpha: float \| None): self.r = r self.g = g self.b = b self.alpha = alpha self._tuple: tuple[float, float, float, float \| None] = (r, g, b, alpha)` | Color [¶](#pydantic_extra_types.color.Color "Permanent link") -------------------------------------------------------------- `Color(value: ColorType)` Bases: `Representation` Represents a color. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93 | `def __init__(self, value: ColorType) -> None: self._rgba: RGBA self._original: ColorType if isinstance(value, (tuple, list)): self._rgba = parse_tuple(value) elif isinstance(value, str): self._rgba = parse_str(value) elif isinstance(value, Color): self._rgba = value._rgba value = value._original else: raise PydanticCustomError( 'color_error', 'value is not a valid color: value must be a tuple, list or string', ) # if we've got here value must be a valid color self._original = value` | ### original [¶](#pydantic_extra_types.color.Color.original "Permanent link") `original() -> ColorType` Original value passed to `Color`. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 103
104
105
106
107 | ``def original(self) -> ColorType: """ Original value passed to `Color`. """ return self._original`` | ### as\_named [¶](#pydantic_extra_types.color.Color.as_named "Permanent link") `as_named(*, fallback: [bool](https://docs.python.org/3/library/functions.html#bool) = False) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary, otherwise returns the hexadecimal representation of the color or raises `ValueError`. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `fallback` | `[bool](https://docs.python.org/3/library/functions.html#bool) ` | If True, falls back to returning the hexadecimal representation of the color instead of raising a ValueError when no named color is found. | `False` | Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The name of the color, or the hexadecimal representation of the color. | Raises: | Type | Description | | --- | --- | | `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` | When no named color is found and fallback is `False`. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 | ``def as_named(self, *, fallback: bool = False) -> str: """ Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary, otherwise returns the hexadecimal representation of the color or raises `ValueError`. Args: fallback: If True, falls back to returning the hexadecimal representation of the color instead of raising a ValueError when no named color is found. Returns: The name of the color, or the hexadecimal representation of the color. Raises: ValueError: When no named color is found and fallback is `False`. """ if self._rgba.alpha is not None: return self.as_hex() rgb = cast(Tuple[int, int, int], self.as_rgb_tuple()) if rgb in COLORS_BY_VALUE: return COLORS_BY_VALUE[rgb] else: if fallback: return self.as_hex() else: raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()')`` | ### as\_hex [¶](#pydantic_extra_types.color.Color.as_hex "Permanent link") `as_hex(format: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ['short', 'long'] = 'short') -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Returns the hexadecimal representation of the color. Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string a "short" representation of the color is possible and whether there's an alpha channel. Returns: | Type | Description | | --- | --- | | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The hexadecimal representation of the color. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152 | `def as_hex(self, format: Literal['short', 'long'] = 'short') -> str: """Returns the hexadecimal representation of the color. Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string a "short" representation of the color is possible and whether there's an alpha channel. Returns: The hexadecimal representation of the color. """ values = [float_to_255(c) for c in self._rgba[:3]] if self._rgba.alpha is not None: values.append(float_to_255(self._rgba.alpha)) as_hex = ''.join(f'{v:02x}' for v in values) if format == 'short' and all(c in repeat_colors for c in values): as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2)) return f'#{as_hex}'` | ### as\_rgb [¶](#pydantic_extra_types.color.Color.as_rgb "Permanent link") `as_rgb() -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Color as an `rgb(, , )` or `rgba(, , , )` string. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 154
155
156
157
158
159
160
161
162
163
164 | ``def as_rgb(self) -> str: """ Color as an `rgb(, , )` or `rgba(, , ,
)` string. """ if self._rgba.alpha is None: return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})' else: return ( f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, ' f'{round(self._alpha_float(), 2)})' )`` | ### as\_rgb\_tuple [¶](#pydantic_extra_types.color.Color.as_rgb_tuple "Permanent link") `as_rgb_tuple(*, alpha: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None) -> ColorTuple` Returns the color as an RGB or RGBA tuple. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `alpha` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to include the alpha channel. There are three options for this input:

* `None` (default): Include alpha only if it's set. (e.g. not `None`)
* `True`: Always include alpha.
* `False`: Always omit alpha. | `None` | Returns: | Type | Description | | --- | --- | | `ColorTuple` | A tuple that contains the values of the red, green, and blue channels in the range 0 to 255. If alpha is included, it is in the range 0 to 1. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 | ``def as_rgb_tuple(self, *, alpha: bool \| None = None) -> ColorTuple: """ Returns the color as an RGB or RGBA tuple. Args: alpha: Whether to include the alpha channel. There are three options for this input: - `None` (default): Include alpha only if it's set. (e.g. not `None`) - `True`: Always include alpha. - `False`: Always omit alpha. Returns: A tuple that contains the values of the red, green, and blue channels in the range 0 to 255. If alpha is included, it is in the range 0 to 1. """ r, g, b = (float_to_255(c) for c in self._rgba[:3]) if alpha is None and self._rgba.alpha is None or alpha is not None and not alpha: return r, g, b else: return r, g, b, self._alpha_float()`` | ### as\_hsl [¶](#pydantic_extra_types.color.Color.as_hsl "Permanent link") `as_hsl() -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Color as an `hsl(, , )` or `hsl(, , ,
)` string. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 187
188
189
190
191
192
193
194
195
196 | ``def as_hsl(self) -> str: """ Color as an `hsl(, , )` or `hsl(, , ,
)` string. """ if self._rgba.alpha is None: h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})' else: h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'`` | ### as\_hsl\_tuple [¶](#pydantic_extra_types.color.Color.as_hsl_tuple "Permanent link") `as_hsl_tuple(*, alpha: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None) -> HslColorTuple` Returns the color as an HSL or HSLA tuple. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `alpha` | `[bool](https://docs.python.org/3/library/functions.html#bool) \| None` | Whether to include the alpha channel.

* `None` (default): Include the alpha channel only if it's set (e.g. not `None`).
* `True`: Always include alpha.
* `False`: Always omit alpha. | `None` | Returns: | Type | Description | | --- | --- | | `HslColorTuple` | The color as a tuple of hue, saturation, lightness, and alpha (if included). All elements are in the range 0 to 1. | Note This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`. Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 | ``def as_hsl_tuple(self, *, alpha: bool \| None = None) -> HslColorTuple: """ Returns the color as an HSL or HSLA tuple. Args: alpha: Whether to include the alpha channel. - `None` (default): Include the alpha channel only if it's set (e.g. not `None`). - `True`: Always include alpha. - `False`: Always omit alpha. Returns: The color as a tuple of hue, saturation, lightness, and alpha (if included). All elements are in the range 0 to 1. Note: This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`. """ h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) if alpha is None: if self._rgba.alpha is None: return h, s, l else: return h, s, l, self._alpha_float() return (h, s, l, self._alpha_float()) if alpha else (h, s, l)`` | parse\_tuple [¶](#pydantic_extra_types.color.parse_tuple "Permanent link") --------------------------------------------------------------------------- `parse_tuple(value: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ...]) -> [RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA")` Parse a tuple or list to get RGBA values. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[tuple](https://docs.python.org/3/library/stdtypes.html#tuple) [[Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") , ...]` | A tuple or list. | _required_ | Returns: | Type | Description | | --- | --- | | `[RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA") ` | An `RGBA` tuple parsed from the input tuple. | Raises: | Type | Description | | --- | --- | | `[PydanticCustomError](../pydantic_core/#pydantic_core.PydanticCustomError "pydantic_core.PydanticCustomError") ` | If tuple is not valid. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271 | ``def parse_tuple(value: tuple[Any, ...]) -> RGBA: """Parse a tuple or list to get RGBA values. Args: value: A tuple or list. Returns: An `RGBA` tuple parsed from the input tuple. Raises: PydanticCustomError: If tuple is not valid. """ if len(value) == 3: r, g, b = (parse_color_value(v) for v in value) return RGBA(r, g, b, None) elif len(value) == 4: r, g, b = (parse_color_value(v) for v in value[:3]) return RGBA(r, g, b, parse_float_alpha(value[3])) else: raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4')`` | parse\_str [¶](#pydantic_extra_types.color.parse_str "Permanent link") ----------------------------------------------------------------------- `parse_str(value: [str](https://docs.python.org/3/library/stdtypes.html#str) ) -> [RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA")` Parse a string representing a color to an RGBA tuple. Possible formats for the input string include: * named color, see `COLORS_BY_NAME` * hex short eg. `fff` (prefix can be `#`, `0x` or nothing) * hex long eg. `ffffff` (prefix can be `#`, `0x` or nothing) * `rgb(, , )` * `rgba(, , ,
)` * `transparent` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | A string representing a color. | _required_ | Returns: | Type | Description | | --- | --- | | `[RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA") ` | An `RGBA` tuple parsed from the input string. | Raises: | Type | Description | | --- | --- | | `[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError) ` | If the input string cannot be parsed to an RGBA tuple. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330 | ``def parse_str(value: str) -> RGBA: """ Parse a string representing a color to an RGBA tuple. Possible formats for the input string include: * named color, see `COLORS_BY_NAME` * hex short eg. `fff` (prefix can be `#`, `0x` or nothing) * hex long eg. `ffffff` (prefix can be `#`, `0x` or nothing) * `rgb(, , )` * `rgba(, , ,
)` * `transparent` Args: value: A string representing a color. Returns: An `RGBA` tuple parsed from the input string. Raises: ValueError: If the input string cannot be parsed to an RGBA tuple. """ value_lower = value.lower() if value_lower in COLORS_BY_NAME: r, g, b = COLORS_BY_NAME[value_lower] return ints_to_rgba(r, g, b, None) m = re.fullmatch(r_hex_short, value_lower) if m: *rgb, a = m.groups() r, g, b = (int(v * 2, 16) for v in rgb) alpha = int(a * 2, 16) / 255 if a else None return ints_to_rgba(r, g, b, alpha) m = re.fullmatch(r_hex_long, value_lower) if m: *rgb, a = m.groups() r, g, b = (int(v, 16) for v in rgb) alpha = int(a, 16) / 255 if a else None return ints_to_rgba(r, g, b, alpha) m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower) if m: return ints_to_rgba(*m.groups()) # type: ignore m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower) if m: return parse_hsl(*m.groups()) # type: ignore if value_lower == 'transparent': return RGBA(0, 0, 0, 0) raise PydanticCustomError( 'color_error', 'value is not a valid color: string not recognised as a valid color', )`` | ints\_to\_rgba [¶](#pydantic_extra_types.color.ints_to_rgba "Permanent link") ------------------------------------------------------------------------------ `ints_to_rgba( r: [int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , g: [int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , b: [int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , alpha: [float](https://docs.python.org/3/library/functions.html#float) | None = None, ) -> [RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA")` Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `r` | `[int](https://docs.python.org/3/library/functions.html#int) \| [str](https://docs.python.org/3/library/stdtypes.html#str) ` | An integer or string representing the red color value. | _required_ | | `g` | `[int](https://docs.python.org/3/library/functions.html#int) \| [str](https://docs.python.org/3/library/stdtypes.html#str) ` | An integer or string representing the green color value. | _required_ | | `b` | `[int](https://docs.python.org/3/library/functions.html#int) \| [str](https://docs.python.org/3/library/stdtypes.html#str) ` | An integer or string representing the blue color value. | _required_ | | `alpha` | `[float](https://docs.python.org/3/library/functions.html#float) \| None` | A float representing the alpha value. Defaults to None. | `None` | Returns: | Type | Description | | --- | --- | | `[RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA") ` | An instance of the `RGBA` class with the corresponding color and alpha values. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356 | ``def ints_to_rgba( r: int \| str, g: int \| str, b: int \| str, alpha: float \| None = None, ) -> RGBA: """ Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object. Args: r: An integer or string representing the red color value. g: An integer or string representing the green color value. b: An integer or string representing the blue color value. alpha: A float representing the alpha value. Defaults to None. Returns: An instance of the `RGBA` class with the corresponding color and alpha values. """ return RGBA( parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha), )`` | parse\_color\_value [¶](#pydantic_extra_types.color.parse_color_value "Permanent link") ---------------------------------------------------------------------------------------- `parse_color_value( value: [int](https://docs.python.org/3/library/functions.html#int) | [str](https://docs.python.org/3/library/stdtypes.html#str) , max_val: [int](https://docs.python.org/3/library/functions.html#int) = 255 ) -> [float](https://docs.python.org/3/library/functions.html#float)` Parse the color value provided and return a number between 0 and 1. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `[int](https://docs.python.org/3/library/functions.html#int) \| [str](https://docs.python.org/3/library/stdtypes.html#str) ` | An integer or string color value. | _required_ | | `max_val` | `[int](https://docs.python.org/3/library/functions.html#int) ` | Maximum range value. Defaults to 255. | `255` | Raises: | Type | Description | | --- | --- | | `[PydanticCustomError](../pydantic_core/#pydantic_core.PydanticCustomError "pydantic_core.PydanticCustomError") ` | If the value is not a valid color. | Returns: | Type | Description | | --- | --- | | `[float](https://docs.python.org/3/library/functions.html#float) ` | A number between 0 and 1. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387 | `def parse_color_value(value: int \| str, max_val: int = 255) -> float: """ Parse the color value provided and return a number between 0 and 1. Args: value: An integer or string color value. max_val: Maximum range value. Defaults to 255. Raises: PydanticCustomError: If the value is not a valid color. Returns: A number between 0 and 1. """ try: color = float(value) except ValueError as e: raise PydanticCustomError( 'color_error', 'value is not a valid color: color values must be a valid number', ) from e if 0 <= color <= max_val: return color / max_val else: raise PydanticCustomError( 'color_error', 'value is not a valid color: color values must be in the range 0 to {max_val}', {'max_val': max_val}, )` | parse\_float\_alpha [¶](#pydantic_extra_types.color.parse_float_alpha "Permanent link") ---------------------------------------------------------------------------------------- `parse_float_alpha( value: None | [str](https://docs.python.org/3/library/stdtypes.html#str) | [float](https://docs.python.org/3/library/functions.html#float) | [int](https://docs.python.org/3/library/functions.html#int) , ) -> [float](https://docs.python.org/3/library/functions.html#float) | None` Parse an alpha value checking it's a valid float in the range 0 to 1. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `value` | `None \| [str](https://docs.python.org/3/library/stdtypes.html#str) \| [float](https://docs.python.org/3/library/functions.html#float) \| [int](https://docs.python.org/3/library/functions.html#int) ` | The input value to parse. | _required_ | Returns: | Type | Description | | --- | --- | | `[float](https://docs.python.org/3/library/functions.html#float) \| None` | The parsed value as a float, or `None` if the value was None or equal 1. | Raises: | Type | Description | | --- | --- | | `[PydanticCustomError](../pydantic_core/#pydantic_core.PydanticCustomError "pydantic_core.PydanticCustomError") ` | If the input value cannot be successfully parsed as a float in the expected range. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424 | ``def parse_float_alpha(value: None \| str \| float \| int) -> float \| None: """ Parse an alpha value checking it's a valid float in the range 0 to 1. Args: value: The input value to parse. Returns: The parsed value as a float, or `None` if the value was None or equal 1. Raises: PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range. """ if value is None: return None try: if isinstance(value, str) and value.endswith('%'): alpha = float(value[:-1]) / 100 else: alpha = float(value) except ValueError as e: raise PydanticCustomError( 'color_error', 'value is not a valid color: alpha values must be a valid float', ) from e if math.isclose(alpha, 1): return None elif 0 <= alpha <= 1: return alpha else: raise PydanticCustomError( 'color_error', 'value is not a valid color: alpha values must be in the range 0 to 1', )`` | parse\_hsl [¶](#pydantic_extra_types.color.parse_hsl "Permanent link") ----------------------------------------------------------------------- `parse_hsl( h: [str](https://docs.python.org/3/library/stdtypes.html#str) , h_units: [str](https://docs.python.org/3/library/stdtypes.html#str) , sat: [str](https://docs.python.org/3/library/stdtypes.html#str) , light: [str](https://docs.python.org/3/library/stdtypes.html#str) , alpha: [float](https://docs.python.org/3/library/functions.html#float) | None = None, ) -> [RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA")` Parse raw hue, saturation, lightness, and alpha values and convert to RGBA. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `h` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The hue value. | _required_ | | `h_units` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The unit for hue value. | _required_ | | `sat` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The saturation value. | _required_ | | `light` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The lightness value. | _required_ | | `alpha` | `[float](https://docs.python.org/3/library/functions.html#float) \| None` | Alpha value. | `None` | Returns: | Type | Description | | --- | --- | | `[RGBA](#pydantic_extra_types.color.RGBA "pydantic_extra_types.color.RGBA") ` | An instance of `RGBA`. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453 | ``def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: float \| None = None) -> RGBA: """ Parse raw hue, saturation, lightness, and alpha values and convert to RGBA. Args: h: The hue value. h_units: The unit for hue value. sat: The saturation value. light: The lightness value. alpha: Alpha value. Returns: An instance of `RGBA`. """ s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100) h_value = float(h) if h_units in {None, 'deg'}: h_value = h_value % 360 / 360 elif h_units == 'rad': h_value = h_value % rads / rads else: # turns h_value %= 1 r, g, b = hls_to_rgb(h_value, l_value, s_value) return RGBA(r, g, b, parse_float_alpha(alpha))`` | float\_to\_255 [¶](#pydantic_extra_types.color.float_to_255 "Permanent link") ------------------------------------------------------------------------------ `float_to_255(c: [float](https://docs.python.org/3/library/functions.html#float) ) -> [int](https://docs.python.org/3/library/functions.html#int)` Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive). Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `c` | `[float](https://docs.python.org/3/library/functions.html#float) ` | The float value to be converted. Must be between 0 and 1 (inclusive). | _required_ | Returns: | Type | Description | | --- | --- | | `[int](https://docs.python.org/3/library/functions.html#int) ` | The integer equivalent of the given float value rounded to the nearest whole number. | Source code in `pydantic_extra_types/color.py` | | | | --- | --- | | 456
457
458
459
460
461
462
463
464
465
466 | `def float_to_255(c: float) -> int: """ Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive). Args: c: The float value to be converted. Must be between 0 and 1 (inclusive). Returns: The integer equivalent of the given float value rounded to the nearest whole number. """ return round(c * 255)` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Mac Address - Pydantic Mac Address =========== The MAC address module provides functionality to parse and validate MAC addresses in different formats, such as IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet format. MacAddress [¶](#pydantic_extra_types.mac_address.MacAddress "Permanent link") ------------------------------------------------------------------------------ Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` Represents a MAC address and provides methods for conversion, validation, and serialization. `from pydantic import BaseModel from pydantic_extra_types.mac_address import MacAddress class Network(BaseModel): mac_address: MacAddress network = Network(mac_address="00:00:5e:00:53:01") print(network) #> mac_address='00:00:5e:00:53:01'` ### validate\_mac\_address `staticmethod` [¶](#pydantic_extra_types.mac_address.MacAddress.validate_mac_address "Permanent link") `validate_mac_address(value: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) ) -> [str](https://docs.python.org/3/library/stdtypes.html#str)` Validate a MAC Address from the provided byte value. Source code in `pydantic_extra_types/mac_address.py` | | | | --- | --- | | 66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 | `@staticmethod def validate_mac_address(value: bytes) -> str: """ Validate a MAC Address from the provided byte value. """ if len(value) < 14: raise PydanticCustomError( 'mac_address_len', 'Length for a {mac_address} MAC address must be {required_length}', {'mac_address': value.decode(), 'required_length': 14}, ) if value[2] in [ord(':'), ord('-')]: if (len(value) + 1) % 3 != 0: raise PydanticCustomError( 'mac_address_format', 'Must have the format xx:xx:xx:xx:xx:xx or xx-xx-xx-xx-xx-xx' ) n = (len(value) + 1) // 3 if n not in (6, 8, 20): raise PydanticCustomError( 'mac_address_format', 'Length for a {mac_address} MAC address must be {required_length}', {'mac_address': value.decode(), 'required_length': (6, 8, 20)}, ) mac_address = bytearray(n) x = 0 for i in range(n): try: byte_value = int(value[x : x + 2], 16) mac_address[i] = byte_value x += 3 except ValueError as e: raise PydanticCustomError('mac_address_format', 'Unrecognized format') from e elif value[4] == ord('.'): if (len(value) + 1) % 5 != 0: raise PydanticCustomError('mac_address_format', 'Must have the format xx.xx.xx.xx.xx.xx') n = 2 * (len(value) + 1) // 5 if n not in (6, 8, 20): raise PydanticCustomError( 'mac_address_format', 'Length for a {mac_address} MAC address must be {required_length}', {'mac_address': value.decode(), 'required_length': (6, 8, 20)}, ) mac_address = bytearray(n) x = 0 for i in range(0, n, 2): try: byte_value = int(value[x : x + 2], 16) mac_address[i] = byte_value byte_value = int(value[x + 2 : x + 4], 16) mac_address[i + 1] = byte_value x += 5 except ValueError as e: raise PydanticCustomError('mac_address_format', 'Unrecognized format') from e else: raise PydanticCustomError('mac_address_format', 'Unrecognized format') return ':'.join(f'{b:02x}' for b in mac_address)` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Pendulum - Pydantic Pendulum ======== Native Pendulum DateTime object implementation. This is a copy of the Pendulum DateTime object, but with a Pydantic CoreSchema implementation. This allows Pydantic to validate the DateTime object. DateTime [¶](#pydantic_extra_types.pendulum_dt.DateTime "Permanent link") -------------------------------------------------------------------------- Bases: `DateTime` A `pendulum.DateTime` object. At runtime, this type decomposes into pendulum.DateTime automatically. This type exists because Pydantic throws a fit on unknown types. `from pydantic import BaseModel from pydantic_extra_types.pendulum_dt import DateTime class test_model(BaseModel): dt: DateTime print(test_model(dt='2021-01-01T00:00:00+00:00')) #> test_model(dt=DateTime(2021, 1, 1, 0, 0, 0, tzinfo=FixedTimezone(0, name="+00:00")))` Date [¶](#pydantic_extra_types.pendulum_dt.Date "Permanent link") ------------------------------------------------------------------ Bases: `Date` A `pendulum.Date` object. At runtime, this type decomposes into pendulum.Date automatically. This type exists because Pydantic throws a fit on unknown types. `from pydantic import BaseModel from pydantic_extra_types.pendulum_dt import Date class test_model(BaseModel): dt: Date print(test_model(dt='2021-01-01')) #> test_model(dt=Date(2021, 1, 1))` Duration [¶](#pydantic_extra_types.pendulum_dt.Duration "Permanent link") -------------------------------------------------------------------------- Bases: `Duration` A `pendulum.Duration` object. At runtime, this type decomposes into pendulum.Duration automatically. This type exists because Pydantic throws a fit on unknown types. `from pydantic import BaseModel from pydantic_extra_types.pendulum_dt import Duration class test_model(BaseModel): delta_t: Duration print(test_model(delta_t='P1DT25H')) #> test_model(delta_t=Duration(days=2, hours=1))` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Script Code - Pydantic Script Code =========== script definitions that are based on the [ISO 15924](https://en.wikipedia.org/wiki/ISO_15924) ISO\_15924 [¶](#pydantic_extra_types.script_code.ISO_15924 "Permanent link") ----------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` ISO\_15924 parses script in the [ISO 15924](https://en.wikipedia.org/wiki/ISO_15924) format. `from pydantic import BaseModel from pydantic_extra_types.language_code import ISO_15924 class Script(BaseModel): alpha_4: ISO_15924 script = Script(alpha_4='Java') print(lang) # > script='Java'` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Semantic Version - Pydantic Semantic Version ================ SemanticVersion definition that is based on the Semantiv Versioning Specification [semver](https://semver.org/) . SemanticVersion [¶](#pydantic_extra_types.semantic_version.SemanticVersion "Permanent link") --------------------------------------------------------------------------------------------- Semantic version based on the official [semver thread](https://python-semver.readthedocs.io/en/latest/advanced/combine-pydantic-and-semver.html) . Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Timezone Name - Pydantic Timezone Name ============= Time zone name validation and serialization module. TimeZoneName [¶](#pydantic_extra_types.timezone_name.TimeZoneName "Permanent link") ------------------------------------------------------------------------------------ Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` TimeZoneName is a custom string subclass for validating and serializing timezone names. The TimeZoneName class uses the IANA Time Zone Database for validation. It supports both strict and non-strict modes for timezone name validation. #### Examples:[¶](#pydantic_extra_types.timezone_name.TimeZoneName--examples "Permanent link") Some examples of using the TimeZoneName class: ##### Normal usage:[¶](#pydantic_extra_types.timezone_name.TimeZoneName--normal-usage "Permanent link") `from pydantic_extra_types.timezone_name import TimeZoneName from pydantic import BaseModel class Location(BaseModel): city: str timezone: TimeZoneName loc = Location(city="New York", timezone="America/New_York") print(loc.timezone) >> America/New_York` ##### Non-strict mode:[¶](#pydantic_extra_types.timezone_name.TimeZoneName--non-strict-mode "Permanent link") `from pydantic_extra_types.timezone_name import TimeZoneName, timezone_name_settings @timezone_name_settings(strict=False) class TZNonStrict(TimeZoneName): pass tz = TZNonStrict("america/new_york") print(tz) >> america/new_york` get\_timezones [¶](#pydantic_extra_types.timezone_name.get_timezones "Permanent link") --------------------------------------------------------------------------------------- `get_timezones() -> [Set](https://docs.python.org/3/library/typing.html#typing.Set "typing.Set") [[str](https://docs.python.org/3/library/stdtypes.html#str) ]` Determine the timezone provider and return available timezones. Source code in `pydantic_extra_types/timezone_name.py` | | | | --- | --- | | 45
46
47
48
49
50
51
52
53
54
55
56 | `def get_timezones() -> Set[str]: """Determine the timezone provider and return available timezones.""" if _is_available('zoneinfo') and _is_available('tzdata'): # pragma: no cover return _tz_provider_from_zone_info() elif _is_available('pytz'): # pragma: no cover if sys.version_info[:2] > (3, 8): _warn_about_pytz_usage() return _tz_provider_from_pytz() else: # pragma: no cover if sys.version_info[:2] == (3, 8): raise ImportError('No pytz module found. Please install it with "pip install pytz"') raise ImportError('No timezone provider found. Please install tzdata with "pip install tzdata"')` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # ULID - Pydantic ULID ==== The `pydantic_extra_types.ULID` module provides the \[`ULID`\] data type. This class depends on the \[python-ulid\] package, which is a validate by the [ULID-spec](https://github.com/ulid/spec#implementations-in-other-languages) . ULID `dataclass` [¶](#pydantic_extra_types.ulid.ULID "Permanent link") ----------------------------------------------------------------------- `ULID(ulid: ULID)` Bases: `Representation` A wrapper around [python-ulid](https://pypi.org/project/python-ulid/) package, which is a validate by the [ULID-spec](https://github.com/ulid/spec#implementations-in-other-languages) . Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # RootModel - Pydantic RootModel ========= RootModel class and type definitions. RootModel [¶](#pydantic.root_model.RootModel "Permanent link") --------------------------------------------------------------- `RootModel( root: RootModelRootType = PydanticUndefined, **data )` Bases: `[BaseModel](../base_model/#pydantic.BaseModel "pydantic.main.BaseModel") `, `[Generic](https://docs.python.org/3/library/typing.html#typing.Generic "typing.Generic") [RootModelRootType]` Usage Documentation [`RootModel` and Custom Root Types](../../concepts/models/#rootmodel-and-custom-root-types) A Pydantic `BaseModel` for the root object of the model. Attributes: | Name | Type | Description | | --- | --- | --- | | `root` | `RootModelRootType` | The root object of the model. | | `__pydantic_root_model__` | | Whether the model is a RootModel. | | `__pydantic_private__` | | Private fields in the model. | | `__pydantic_extra__` | | Extra fields in the model. | Source code in `pydantic/root_model.py` | | | | --- | --- | | 63
64
65
66
67
68
69
70
71 | `def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore __tracebackhide__ = True if data: if root is not PydanticUndefined: raise ValueError( '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments' ) root = data # type: ignore self.__pydantic_validator__.validate_python(root, self_instance=self)` | ### model\_construct `classmethod` [¶](#pydantic.root_model.RootModel.model_construct "Permanent link") `model_construct( root: RootModelRootType, _fields_set: [set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] | None = None, ) -> Self` Create a new model using the provided root object and update fields set. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `root` | `RootModelRootType` | The root object of the model. | _required_ | | `_fields_set` | `[set](https://docs.python.org/3/reference/expressions.html#set) [[str](https://docs.python.org/3/library/stdtypes.html#str) ] \| None` | The set of fields to be updated. | `None` | Returns: | Type | Description | | --- | --- | | `Self` | The new model. | Raises: | Type | Description | | --- | --- | | `[NotImplemented](https://docs.python.org/3/library/constants.html#NotImplemented) ` | If the model is not a subclass of `RootModel`. | Source code in `pydantic/root_model.py` | | | | --- | --- | | 75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 | ``@classmethod def model_construct(cls, root: RootModelRootType, _fields_set: set[str] \| None = None) -> Self: # type: ignore """Create a new model using the provided root object and update fields set. Args: root: The root object of the model. _fields_set: The set of fields to be updated. Returns: The new model. Raises: NotImplemented: If the model is not a subclass of `RootModel`. """ return super().model_construct(root=root, _fields_set=_fields_set)`` | ### model\_dump [¶](#pydantic.root_model.RootModel.model_dump "Permanent link") `model_dump( *, mode: [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["json", "python"] | [str](https://docs.python.org/3/library/stdtypes.html#str) = "python", include: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = None, exclude: [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") = None, context: [dict](https://docs.python.org/3/reference/expressions.html#dict) [[str](https://docs.python.org/3/library/stdtypes.html#str) , [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any") ] | None = None, by_alias: [bool](https://docs.python.org/3/library/functions.html#bool) | None = None, exclude_unset: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_defaults: [bool](https://docs.python.org/3/library/functions.html#bool) = False, exclude_none: [bool](https://docs.python.org/3/library/functions.html#bool) = False, round_trip: [bool](https://docs.python.org/3/library/functions.html#bool) = False, warnings: ( [bool](https://docs.python.org/3/library/functions.html#bool) | [Literal](https://docs.python.org/3/library/typing.html#typing.Literal "typing.Literal") ["none", "warn", "error"] ) = True, serialize_as_any: [bool](https://docs.python.org/3/library/functions.html#bool) = False ) -> [Any](https://docs.python.org/3/library/typing.html#typing.Any "typing.Any")` This method is included just to get a more accurate return type for type checkers. It is included in this `if TYPE_CHECKING:` block since no override is actually necessary. See the documentation of `BaseModel.model_dump` for more details about the arguments. Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could even be something different, in the case of a custom serializer. Thus, `Any` is used here to catch all of these cases. Source code in `pydantic/root_model.py` | | | | --- | --- | | 121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147 | ``def model_dump( # type: ignore self, *, mode: Literal['json', 'python'] \| str = 'python', include: Any = None, exclude: Any = None, context: dict[str, Any] \| None = None, by_alias: bool \| None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, warnings: bool \| Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False, ) -> Any: """This method is included just to get a more accurate return type for type checkers. It is included in this `if TYPE_CHECKING:` block since no override is actually necessary. See the documentation of `BaseModel.model_dump` for more details about the arguments. Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could even be something different, in the case of a custom serializer. Thus, `Any` is used here to catch all of these cases. """ ...`` | Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top --- # Language - Pydantic Language ======== Language definitions that are based on the [ISO 639-3](https://en.wikipedia.org/wiki/ISO_639-3) & [ISO 639-5](https://en.wikipedia.org/wiki/ISO_639-5) . LanguageInfo `dataclass` [¶](#pydantic_extra_types.language_code.LanguageInfo "Permanent link") ------------------------------------------------------------------------------------------------ `LanguageInfo( alpha2: [Union](https://docs.python.org/3/library/typing.html#typing.Union "typing.Union") [[str](https://docs.python.org/3/library/stdtypes.html#str) , None], alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str) , name: [str](https://docs.python.org/3/library/stdtypes.html#str) )` LanguageInfo is a dataclass that contains the language information. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `alpha2` | `[Union](https://docs.python.org/3/library/typing.html#typing.Union "typing.Union") [[str](https://docs.python.org/3/library/stdtypes.html#str) , None]` | The language code in the [ISO 639-1 alpha-2](https://en.wikipedia.org/wiki/ISO_639-1)
format. | _required_ | | `alpha3` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The language code in the [ISO 639-3 alpha-3](https://en.wikipedia.org/wiki/ISO_639-3)
format. | _required_ | | `name` | `[str](https://docs.python.org/3/library/stdtypes.html#str) ` | The language name. | _required_ | LanguageAlpha2 [¶](#pydantic_extra_types.language_code.LanguageAlpha2 "Permanent link") ---------------------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` LanguageAlpha2 parses languages codes in the [ISO 639-1 alpha-2](https://en.wikipedia.org/wiki/ISO_639-1) format. `from pydantic import BaseModel from pydantic_extra_types.language_code import LanguageAlpha2 class Movie(BaseModel): audio_lang: LanguageAlpha2 subtitles_lang: LanguageAlpha2 movie = Movie(audio_lang='de', subtitles_lang='fr') print(movie) #> audio_lang='de' subtitles_lang='fr'` ### alpha3 `property` [¶](#pydantic_extra_types.language_code.LanguageAlpha2.alpha3 "Permanent link") `alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str)` The language code in the [ISO 639-3 alpha-3](https://en.wikipedia.org/wiki/ISO_639-3) format. ### name `property` [¶](#pydantic_extra_types.language_code.LanguageAlpha2.name "Permanent link") `name: [str](https://docs.python.org/3/library/stdtypes.html#str)` The language name. LanguageName [¶](#pydantic_extra_types.language_code.LanguageName "Permanent link") ------------------------------------------------------------------------------------ Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` LanguageName parses languages names listed in the [ISO 639-3 standard](https://en.wikipedia.org/wiki/ISO_639-3) format. `from pydantic import BaseModel from pydantic_extra_types.language_code import LanguageName class Movie(BaseModel): audio_lang: LanguageName subtitles_lang: LanguageName movie = Movie(audio_lang='Dutch', subtitles_lang='Mandarin Chinese') print(movie) #> audio_lang='Dutch' subtitles_lang='Mandarin Chinese'` ### alpha2 `property` [¶](#pydantic_extra_types.language_code.LanguageName.alpha2 "Permanent link") `alpha2: [Union](https://docs.python.org/3/library/typing.html#typing.Union "typing.Union") [[str](https://docs.python.org/3/library/stdtypes.html#str) , None]` The language code in the [ISO 639-1 alpha-2](https://en.wikipedia.org/wiki/ISO_639-1) format. Does not exist for all languages. ### alpha3 `property` [¶](#pydantic_extra_types.language_code.LanguageName.alpha3 "Permanent link") `alpha3: [str](https://docs.python.org/3/library/stdtypes.html#str)` The language code in the [ISO 639-3 alpha-3](https://en.wikipedia.org/wiki/ISO_639-3) format. ISO639\_3 [¶](#pydantic_extra_types.language_code.ISO639_3 "Permanent link") ----------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` ISO639\_3 parses Language in the [ISO 639-3 alpha-3](https://en.wikipedia.org/wiki/ISO_639-3_alpha-3) format. `from pydantic import BaseModel from pydantic_extra_types.language_code import ISO639_3 class Language(BaseModel): alpha_3: ISO639_3 lang = Language(alpha_3='ssr') print(lang) # > alpha_3='ssr'` ISO639\_5 [¶](#pydantic_extra_types.language_code.ISO639_5 "Permanent link") ----------------------------------------------------------------------------- Bases: `[str](https://docs.python.org/3/library/stdtypes.html#str) ` ISO639\_5 parses Language in the [ISO 639-5 alpha-3](https://en.wikipedia.org/wiki/ISO_639-5_alpha-3) format. `from pydantic import BaseModel from pydantic_extra_types.language_code import ISO639_5 class Language(BaseModel): alpha_3: ISO639_5 lang = Language(alpha_3='gem') print(lang) # > alpha_3='gem'` Was this page helpful? Thanks for your feedback! Thanks for your feedback! Back to top ---