typestar

Field constraints in Python

Field carries the bounds, so validation lives with the declaration.

from pydantic import BaseModel, Field, ValidationError


class Step(BaseModel):
    title: str = Field(max_length=60)
    stars: int = Field(default=0, ge=0, le=3)
    target_tpm: int = Field(alias="tpm3", gt=0, description="3-star bar")


step = Step(title="Slices", stars=2, tpm3=95)
print(step.stars, step.target_tpm)

try:
    Step(title="x", stars=9, tpm3=95)
except ValidationError as exc:
    print(exc.errors()[0]["msg"])

How it works

  1. ge, le and max_length are checked before your code runs.
  2. alias maps an incoming key to a different attribute name.
  3. description and examples end up in the generated schema.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
409
Tokens
131
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 2 of 5 in Pydantic models, step 2 of 19 in Web services & data access.

← Previous Next →