Don’t Write Another Line of Code Until You See These Pydantic V2 Breakthrough Features
<p><a href="https://docs.pydantic.dev/latest/" rel="noopener ugc nofollow" target="_blank">Pydantic</a> is the go-to data validation python library. With about <a href="https://pypistats.org/packages/pydantic" rel="noopener ugc nofollow" target="_blank">20 million downloads per week</a>, it is among the <a href="https://hugovk.github.io/top-pypi-packages/" rel="noopener ugc nofollow" target="_blank">top 100 python libraries</a>.</p>
<p>Pydantic V2 was recently released (with a rust backend) — it is <a href="https://docs.pydantic.dev/latest/blog/pydantic-v2-alpha/#headlines" rel="noopener ugc nofollow" target="_blank">5–50X faster than V1</a>! The release also introduces many new breakthrough features, of which I will be discussing.</p>
<h1>Validating Functions</h1>
<p>Pydantic V2 allows you to validate any <a href="https://docs.pydantic.dev/latest/usage/validation_decorator/" rel="noopener ugc nofollow" target="_blank">function’s arguments</a>! <em>(Yes, including class methods.)</em></p>
<p> </p>
<h1>2. Discriminated Unions</h1>
<p>Discriminated unions are union operators which determine which model or value to use, based on <a href="https://docs.pydantic.dev/latest/usage/types/unions/#discriminated-unions-aka-tagged-unions" rel="noopener ugc nofollow" target="_blank">discriminator field</a>. This is especially useful for <a href="https://fastapi.tiangolo.com/" rel="noopener ugc nofollow" target="_blank">FastAPI</a> developers who may need to return different models from an API endpoint, given different request parameters.</p>
<h1>3. Validated Types with Annotated Validators</h1>
<p>Validation no longer needs to be bound to a model! With <a href="https://docs.pydantic.dev/latest/usage/validators/#annotated-validators" rel="noopener ugc nofollow" target="_blank">Annotated Validators</a>, you can create a validator on a field (i.e. type) directly. <em>(Implicit decorators, be gone!)</em></p>
<p>This is helpful if your validation is specific to a field — or if you want share this validation between modules.</p>
<p>Here’s a simple example of a custom type, <code>PositiveNumber</code>, which only accepts positive numbers as input</p>
<h2>Sharing fields between models & modules:</h2>
<p>Annotated Validators unlocks the sharing of fields between models and modules — since custom types contain validators on the object themselves!</p>
<p>This declarative approach is a major enhancement and a major boon for python developers working with custom types.</p>
<p><a href="https://blog.det.life/dont-write-another-line-of-code-until-you-see-these-pydantic-v2-breakthrough-features-5cdc65e6b448">Website</a></p>