Pydantic is a Python library used for data parsing and validation through Python type annotations. It’s particularly useful for enforcing that input data matches a specific format, type, or set of constraints.
In this approach, you define a class that directly inherits from Pydantic’s BaseModel. The class properties are declared as class variables with type annotations. Pydantic will automatically handle validation based on these annotations.
from pydantic import BaseModel, validator
In this example, User inherits from BaseModel, and each field (name, age, email) is automatically validated. The custom validator for the age field ensures that the age is at least 18.
In this approach, you define a separate Pydantic model for data validation, and then use this model within the init method of your custom class to validate the inputs.
from pydantic import BaseModel, ValidationError
In this example, UserInput is a Pydantic model used for validation, while User is a regular Python class. The
__init__ method of User creates an instance of UserInput for validation, and if the data is valid, it proceeds to initialize the User instance.
Both methods are effective for ensuring that the input data adheres to the specified format and constraints. The choice between them depends on your specific use case and design preferences.