Usage with devtools
Note
Admission: I (the primary developer of pydantic) also develop python-devtools.
python-devtools (pip install devtools
) provides a number of tools which
are useful during Python development, including debug()
an alternative to print()
which formats output in a way
which should be easier to read than print
as well as giving information about which file/line the print statement
is on and what value was printed.
pydantic integrates with devtools by implementing the __pretty__
method on most public classes.
In particular debug()
is useful when inspecting models:
from datetime import datetime
from typing import List
from pydantic import BaseModel
from devtools import debug
class Address(BaseModel):
street: str
country: str
lat: float
lng: float
class User(BaseModel):
id: int
name: str
signup_ts: datetime
friends: List[int]
address: Address
user = User(
id='123',
name='John Doe',
signup_ts='2019-06-01 12:22',
friends=[1234, 4567, 7890],
address=dict(street='Testing', country='uk', lat=51.5, lng=0),
)
debug(user)
print('\nshould be much easier read than:\n')
print('user:', user)
from datetime import datetime
from pydantic import BaseModel
from devtools import debug
class Address(BaseModel):
street: str
country: str
lat: float
lng: float
class User(BaseModel):
id: int
name: str
signup_ts: datetime
friends: list[int]
address: Address
user = User(
id='123',
name='John Doe',
signup_ts='2019-06-01 12:22',
friends=[1234, 4567, 7890],
address=dict(street='Testing', country='uk', lat=51.5, lng=0),
)
debug(user)
print('\nshould be much easier read than:\n')
print('user:', user)
(This script is complete, it should run "as is")
Will output in your terminal:
docs/examples/devtools_main.py:31 <module> user: User( id=123, name='John Doe', signup_ts=datetime.datetime(2019, 6, 1, 12, 22), friends=[ 1234, 4567, 7890, ], address=Address( street='Testing', country='uk', lat=51.5, lng=0.0, ), ) (User) should be much easier read than: user: id=123 name='John Doe' signup_ts=datetime.datetime(2019, 6, 1, 12, 22) friends=[1234, 4567, 7890] address=Address(street='Testing', country='uk', lat=51.5, lng=0.0)