和devtools一起使用
Note
承认: 我(pydantic 的主要开发人员)也开发了 python-devtools。
python-devtools (pip install devtools
) 提供了许多在 Python 开发过程中非常有用的工具,包括debug()
作为print( )
以比 print
更容易阅读的方式格式化输出,并提供有关打印语句所在的文件/行以及打印的值的信息。
pydantic 通过在大多数公共类上实现 __pretty__
方法与 devtools 集成。
特别是 debug()
在检查模型时很有用:
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)
(这个脚本是完整的,它应该“按原样”运行)
将在您的终端输出:
docs/examples/devtools_main.py:31 <module> (executing failed to find the calling node) 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)