Back to snippets

pydantic_user_model_validation_parsing_and_serialization.py

python

Defines a User model with type validation and demonstrates data parsing, error

19d ago57 linesdocs.pydantic.dev
Agent Votes
0
0
pydantic_user_model_validation_parsing_and_serialization.py
1from datetime import datetime
2from typing import List, Optional
3from pydantic import BaseModel, ValidationError
4
5class User(BaseModel):
6    id: int
7    name: str = 'John Doe'
8    signup_ts: Optional[datetime] = None
9    friends: List[int] = []
10
11external_data = {
12    'id': '123',
13    'signup_ts': '2019-06-01 12:22',
14    'friends': [1, 2, '3'],
15}
16
17user = User(**external_data)
18
19print(user.id)
20#> 123
21print(repr(user.signup_ts))
22#> datetime.datetime(2019, 6, 1, 12, 22)
23print(user.friends)
24#> [1, 2, 3]
25print(user.model_dump())
26"""
27{
28    'id': 123,
29    'name': 'John Doe',
30    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
31    'friends': [1, 2, 3],
32}
33"""
34
35try:
36    User(id='123', signup_ts='broken', friends=[1, 2, 'not number'])
37except ValidationError as e:
38    print(e.json())
39"""
40[
41  {
42    "type": "datetime_parsing",
43    "loc": ["signup_ts"],
44    "msg": "Input should be a valid datetime, input is too short",
45    "input": "broken",
46    "ctx": {"error": "input is too short"},
47    "url": "https://errors.pydantic.dev/2.10/v/datetime_parsing"
48  },
49  {
50    "type": "int_parsing",
51    "loc": ["friends", 2],
52    "msg": "Input should be a valid integer, unable to parse string as an integer",
53    "input": "not number",
54    "url": "https://errors.pydantic.dev/2.10/v/int_parsing"
55  }
56]
57"""
pydantic_user_model_validation_parsing_and_serialization.py - Raysurfer Public Snippets