Krystal
04/30/2024, 3:26 PMMarvin
04/30/2024, 3:27 PMpython
from prefect import flow
from pydantic import BaseModel, validator
from typing import Literal
# Define your Pydantic model
class Model(BaseModel):
a: int
b: float
c: str
# Use the Pydantic model as a type hint in your flow
@flow
def model_validator_flow(model: Model):
print(model)
# You can also use Pydantic validators for more complex validations
class ShirtOrder(BaseModel):
size: Literal["small", "medium", "large", "xlarge"]
color: Literal["red", "green", "black"]
@validator("color")
def validate_color(cls, value, values, **kwargs):
if value == "green" and values["size"] == "small":
raise ValueError(
"Green is only in-stock for medium, large, and XL sizes."
)
return value
# Then you could use this model in a flow as well
@flow
def shirt_order_flow(order: ShirtOrder):
print(order)
When you invoke your flow, the input parameters will be automatically validated against the Pydantic model. Incorrect types or failed custom validations will raise an error.
Here are some links to the documentation sections that cover this topic:
- Using Type Hints in Flows
- Handling Custom Validation
Ensure that you use Prefect 2.x syntax, as Prefect 1.x has different ways of handling these operations.Krystal
04/30/2024, 3:35 PM@validator("attr_1")
def validate_mutually_exclusive(cls, v, values):
if v is None and values.get("attr_2") is None:
raise ValueError(
"attr_1 and attr_2 are mutually exclusive. One of them must can be set."
)
return v