Skip to content

Description:

  • Data validation using Python type hints.

Resources:

Source and license:

Validate a custom model

from datetime import datetime
from pydantic import ValidationError
from pydantic import BaseModel, PositiveInt
from typing import Optional
class User(BaseModel):
id: int
name: str = 'John Doe'
signup_ts: Optional[datetime]
tastes: dict[str, PositiveInt]
external_data = {'id': 'not an int', 'tastes': {}}
try:
User(**external_data)
except ValidationError as e:
print(e.errors())
"""
[
{
'type': 'int_parsing',
'loc': ('id',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not an int',
'url': 'https://errors.pydantic.dev/2/v/int_parsing',
},
{
'type': 'missing',
'loc': ('signup_ts',),
'msg': 'Field required',
'input': {'id': 'not an int', 'tastes': {}},
'url': 'https://errors.pydantic.dev/2/v/missing',
},
]
"""

ganymede is made by Eugo