Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Practice: Pydantic Exercises

Six hands-on Pydantic exercises with runnable starter code and full solutions: constraints, validators, settings, discriminated unions, serialization and a mini-API model.

The fastest way to learn Pydantic is to write models and watch them accept and reject data. These six exercises follow the chapters of this track. Each one gives you a starter editor that runs right away and prints PASS or FAIL for a set of checks. Edit the model until every line says PASS. Try hard before you open the solutions at the end; a failing check is information, not a problem.

Every exercise uses the same tiny helper, so the output is easy to read:

Python
def check(label, condition):
    print("PASS" if condition else "FAIL", "-", label)

Exercise 1: constraints on a signup form

Make Signup accept a username of 3 to 12 letters or digits (stored lowercase), an age from 13 to 120, and reject unknown keys. Right now the model accepts everything.

Python Exercise 1: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hints: Field(min_length=..., max_length=..., pattern=...), ConfigDict(extra="forbid", str_to_lower=True).

Exercise 2: a cross-field rule

An Event has start and end datetimes. The end must be later than the start, and an event may not last more than 8 hours. Report one clear error message.

Python Exercise 2: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hint: a @model_validator(mode="after") method that compares self.end - self.start with timedelta(hours=8).

Exercise 3: a reusable type

Create Tags, a reusable type: a list of strings that accepts either a list or a comma-separated string, lowercases and strips every tag, removes duplicates keeping the first occurrence order, and allows at most 5 tags.

Python Exercise 3: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hints: BeforeValidator to split and normalize, AfterValidator to remove duplicates, Field(max_length=5) inside Annotated.

Exercise 4: discriminated union

Messages arrive as dictionaries with a type of "text", "image" or "location". Model them as a union that picks the right class by type, so Message.validate_python(...) returns the matching object.

Python Exercise 4: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hint: give each class a type: Literal["..."] field and use Field(discriminator="type") inside Annotated[Text | Image | Location, ...].

Exercise 5: settings with a production rule

Complete Settings: read APP_PORT (1 to 65535, default 8000), a SecretStr named token from APP_TOKEN, and refuse environment="prod" when the token is empty.

Python Exercise 5: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 6: serialization for an API

Product is stored with a cost (what the shop paid) that must never be shown to customers. Make model_dump() skip cost, write the price as a string with two decimals in JSON, and allow reading the field unitPrice from input.

Python Exercise 6: starter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hints: Field(exclude=True), a @field_serializer("price"), and Field(validation_alias="unitPrice") (add validate_by_name=True so price= still works).

Solutions

Open each only after trying. They are runnable, so you can compare output with your attempt.

Solution 1

Python Solution 1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern allows both cases so the lowercase conversion can happen; str_to_lower runs before the pattern check, so a stricter ^[a-z0-9]+$ would work too.

Solution 2

Python Solution 2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution 3

Python Solution 3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

dict.fromkeys removes duplicates while keeping the first occurrence order. The max_length check runs on the already de-duplicated list.

Solution 4

Python Solution 4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution 5

Python Solution 5

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution 6

Python Solution 6

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which tool is best for a rule that compares end and start of an event?

    Rules over several fields need the whole model, and after mode gives you a finished instance.
  2. 2. Which Pydantic feature picks the right class from a tag field such as type?

    The discriminator names the tag field, so Pydantic selects one union member directly.
  3. 3. How do you keep a field out of model_dump() output?

    exclude=True removes the field from dumps and JSON output.

Summary

  • Small, checkable exercises are the quickest way to find gaps in your understanding.
  • You practiced constraints, cross-field rules, reusable Annotated types, discriminated unions, settings with production rules and serialization control.
  • When a check fails, read the ValidationError details: the loc and type usually tell you exactly what to fix.

Back to the track: Pydantic