mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
add pretty print for models (#42)
This commit is contained in:
@@ -6,6 +6,7 @@ History
|
||||
v0.2.0 (TBC)
|
||||
............
|
||||
* allow annotation only fields to support mypy
|
||||
* add pretty ``to_string(pretty=True)`` method for models
|
||||
|
||||
v0.1.0 (2017-06-03)
|
||||
...................
|
||||
|
||||
+20
-2
@@ -201,6 +201,24 @@ class BaseModel(metaclass=MetaModel):
|
||||
def __repr__(self):
|
||||
return f'<{self}>'
|
||||
|
||||
@classmethod
|
||||
def _truncate(cls, v):
|
||||
max_len = 80
|
||||
if isinstance(v, str) and len(v) > (max_len - 2):
|
||||
# 45 so quote + string + ... + quote has length 50
|
||||
return repr(v[:(max_len - 5)] + '...')
|
||||
v = repr(v)
|
||||
if len(v) > max_len:
|
||||
v = v[:max_len - 3] + '...'
|
||||
return v
|
||||
|
||||
def to_string(self, pretty=False):
|
||||
divider = '\n ' if pretty else ' '
|
||||
return '{}{}{}'.format(
|
||||
self.__class__.__name__,
|
||||
divider,
|
||||
divider.join('{}={}'.format(k, self._truncate(v)) for k, v in self.__values__.items()),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return '{} {}'.format(self.__class__.__name__, ' '.join('{}={!r}'.format(k, v)
|
||||
for k, v in self.__values__.items()))
|
||||
return self.to_string()
|
||||
|
||||
@@ -51,6 +51,26 @@ def test_ultra_simple_repr():
|
||||
assert dict(m) == {'a': 10.2, 'b': 10}
|
||||
|
||||
|
||||
def test_str_truncate():
|
||||
class Model(BaseModel):
|
||||
s1: str
|
||||
s2: str
|
||||
b1: bytes
|
||||
b2: bytes
|
||||
m = Model(s1='132', s2='x' * 100, b1='123', b2='x' * 100)
|
||||
print(repr(m.to_string()))
|
||||
assert m.to_string() == ("Model s1='132' "
|
||||
"s2='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...' "
|
||||
"b1=b'123' "
|
||||
"b2=b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...")
|
||||
assert """\
|
||||
Model
|
||||
s1='132'
|
||||
s2='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...'
|
||||
b1=b'123'
|
||||
b2=b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...""" == m.to_string(pretty=True)
|
||||
|
||||
|
||||
def test_comparing():
|
||||
m = UltraSimpleModel(a=10.2, b='100')
|
||||
assert m == {'a': 10.2, 'b': 100}
|
||||
|
||||
Reference in New Issue
Block a user