Creating a new data object#
Creating a new data object with Pydantic involves defining a Python class that inherits from pydantic.BaseModel
.
This class acts as a blueprint for instances of the data object, specifying the attributes and their types.
The keys steps and requirements for creating a new acoupi data objects are the following:
Step 1: In /src/acoupi/data.py
define a data object class that inherit from BaseModel
.
New Data Object.
Step 2: Declare the attributes of the new data object as the class variables. Specify the attributes' data types using Python type hints. Optionally, set default values for the attributes.
Adding Attributes.
Step 3 (Optional): Implement custom validation logic using Pydantic's validation methods such as @field_validatior
and @model_validator
.
Add custom validation logic
from pydantic import BaseModel, field_validator
class YourDataObject(BaseModel):
attribute1: int = 0.5
attribute2: str
@field_validator("attribute1")
def validate_attribute1(cls, value):
"""Check that attribute1 is a float between 0 and 1."""
if value < 0 or value > 1:
raise ValueError("attribute1 must be between 0 and 1")
return value