PythiloLesson 19 of 20 · progress kept in this browser

Keep invariants when fields change

Validation at construction does not automatically validate every later assignment. A model that begins valid can otherwise be changed into an invalid state. Enable assignment validation when a mutable model must preserve its field rules after construction.

Another choice is a frozen model and explicit reconstruction. Neither choice makes nested mutable containers deeply immutable. Also, model_copy(update=...) is a trusted-data operation, not a general replacement for validating untrusted updates. Select the update boundary deliberately and test that rejected updates leave the previous value intact.

from pydantic import BaseModel, ConfigDict
from pydantic import Field, ValidationError
class Counter(BaseModel):
    model_config = ConfigDict(
        validate_assignment=True)
    count: int = Field(ge=0)
item = Counter(count=2)
try:
    item.count = -1
except ValidationError:
    print(item.count)
Your task

Implement update_count(initial,new) using a Counter model with count>=0 and validate_assignment=True. Return (accepted, final_count), catching a rejected assignment but allowing invalid initial construction to raise.

The first run loads pydantic into this browser.