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>&nbsp;is the go-to data validation python library. With about&nbsp;<a href="https://pypistats.org/packages/pydantic" rel="noopener ugc nofollow" target="_blank">20 million downloads per week</a>, it is among the&nbsp;<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) &mdash; it is&nbsp;<a href="https://docs.pydantic.dev/latest/blog/pydantic-v2-alpha/#headlines" rel="noopener ugc nofollow" target="_blank">5&ndash;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&nbsp;<a href="https://docs.pydantic.dev/latest/usage/validation_decorator/" rel="noopener ugc nofollow" target="_blank">function&rsquo;s arguments</a>!&nbsp;<em>(Yes, including class methods.)</em></p> <p>&nbsp;</p> <h1>2. Discriminated Unions</h1> <p>Discriminated unions are union operators which determine which model or value to use, based on&nbsp;<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&nbsp;<a href="https://fastapi.tiangolo.com/" rel="noopener ugc nofollow" target="_blank">FastAPI</a>&nbsp;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&nbsp;<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.&nbsp;<em>(Implicit decorators, be gone!)</em></p> <p>This is helpful if your validation is specific to a field &mdash; or if you want share this validation between modules.</p> <p>Here&rsquo;s a simple example of a custom type,&nbsp;<code>PositiveNumber</code>, which only accepts positive numbers as input</p> <h2>Sharing fields between models &amp; modules:</h2> <p>Annotated Validators unlocks the sharing of fields between models and modules &mdash; 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>