Two Ways of Enforcing and Validating Python class input using Pydantic


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.

Example 1: Defining a Class Directly with Pydantic BaseModel

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

class User(BaseModel):
name: str
age: int
email: str

@validator('age')
def validate_age(cls, v):
if v < 18:
raise ValueError('Age must be at least 18')
return v

# Example usage
try:
user = User(name="John Doe", age=17, email="john@example.com")
except ValueError as e:
print(e)

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.

Example 2: Using a Pydantic Model for Validation in a Custom Class

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

class UserInput(BaseModel):
name: str
age: int
email: str

class User:
def __init__(self, name: str, age: int, email: str):
try:
validated_data = UserInput(name=name, age=age, email=email)
self.name = validated_data.name
self.age = validated_data.age
self.email = validated_data.email
except ValidationError as e:
print("Invalid input:", e.json())

# Example usage
user = User(name="Jane Doe", age=25, email="jane@example.com")

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.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC