Reusing Validators in Pydantic V2: A Guide

Posted by

How to reuse validators on Pydantic V2

How to reuse validators on Pydantic V2

Pydantic is a data validation and settings management library for Python. It is especially useful for data validation in web applications and APIs. With the release of Pydantic V2, reusing validators has become even more convenient and flexible.

Defining validators in Pydantic V2

Validators in Pydantic V2 are defined using the @validator decorator, which allows you to define custom validation logic for a particular field in a Pydantic model.

Reusing validators

In Pydantic V2, you can reuse validators by defining them as standalone functions and then applying them to multiple fields in different models. This allows you to maintain a single source of truth for your validation logic and easily apply it across your application.

Example

Let’s say you have a validator for email address validation:


    from pydantic import BaseModel, validator

    def validate_email(email):
        if "@" not in email:
            raise ValueError("Invalid email address")
        return email

    class User(BaseModel):
        email: str

        @validator("email")
        def validate_email(cls, v):
            return validate_email(v)
    

Now, if you want to reuse the validate_email validator in another model, you can simply import the function and apply it using the @validator decorator:


    from pydantic import BaseModel, validator
    from my_module import validate_email

    class AnotherModel(BaseModel):
        email: str

        @validator("email")
        def validate_email(cls, v):
            return validate_email(v)
    

Conclusion

By defining validators as standalone functions and reusing them across different Pydantic models, you can improve code reusability and maintainability in your application. Pydantic V2 provides a powerful and flexible way to handle data validation, making it easier to write clean and organized code.

0 0 votes
Article Rating
9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jlp2011
10 months ago

good vid. but very hard to read on a small phone. pls zoom in a bit on your editor and font size, the rest of the desktop and tabs is of no great interest.

@user-se1yi9cp5l
10 months ago

Good stuff. Looking forward to the next as well.

@TharlesAmaro1
10 months ago

Very nice

@ihgnmah
10 months ago

Great content. Thank you. I hope you can post more videos regularly.

@tjanos88
10 months ago

Great content 👍

@maroben225
10 months ago

Goood work

@josemuniz5530
10 months ago

Out of curiosity, how would you decide that v2 is ready for use in production? I like a lot of what I see already, but I'm not sure how to understand its "alpha" status.

@raheelsiddiqui1520
10 months ago

This is amazing, Thanks for sharing it

@__sassan__
10 months ago

Great video! I would suggest zooming a bit the editor because on mobile is a bit hard to read (had to zoom)