sample_python_pydantic.py 828 B

12345678910111213141516171819202122232425262728293031323334353637
  1. from datetime import datetime
  2. from pydantic import BaseModel, PositiveInt
  3. from pydantic.version import check_pydantic_core_version
  4. # pydantic pins an exact version of pydantic core
  5. # verify these are in sync in buildroots packaging
  6. assert check_pydantic_core_version()
  7. class User(BaseModel):
  8. id: int
  9. name: str = "John Doe"
  10. signup_ts: datetime | None
  11. tastes: dict[str, PositiveInt]
  12. external_data = {
  13. "id": 123,
  14. "signup_ts": "2019-06-01 12:22",
  15. "tastes": {
  16. "wine": 9,
  17. b"cheese": 7,
  18. "cabbage": "1",
  19. },
  20. }
  21. user = User(**external_data)
  22. expected_user_dump = {
  23. "id": 123,
  24. "name": "John Doe",
  25. "signup_ts": datetime(2019, 6, 1, 12, 22),
  26. "tastes": {"wine": 9, "cheese": 7, "cabbage": 1},
  27. }
  28. assert user.id == 123
  29. assert user.model_dump() == expected_user_dump