Skip to content

Commit 816cdde

Browse files
authored
__pretty__ method in pydantic (#59)
* __pretty__ method in pydantic, fix #54 * add tests
1 parent a506842 commit 816cdde

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ jobs:
5151
env_vars: EXTRAS,PYTHON,OS
5252

5353
- name: uninstall extras
54-
run: pip uninstall -y multidict numpy
54+
run: pip uninstall -y multidict numpy pydantic
5555

5656
- name: test without extras
5757
run: |

devtools/prettier.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ def _format(self, value: Any, indent_current: int, indent_first: bool):
9595
except AttributeError:
9696
pass
9797
else:
98-
if hasattr(pretty_func, '__self__') and not isinstance(value, MockCall):
98+
# `pretty_func.__class__.__name__ == 'method'` should only be true for bound methods,
99+
# `hasattr(pretty_func, '__self__')` is more canonical but weirdly is true for unbound cython functions
100+
if pretty_func.__class__.__name__ == 'method' and not isinstance(value, MockCall):
99101
try:
100102
gen = pretty_func(fmt=fmt, skip_exc=SkipPretty)
101103
self._render_pretty(gen, indent_current)

tests/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ isort==4.3.17
55
pycodestyle==2.6.0
66
pyflakes==2.2.0
77
Pygments==2.6.1
8+
pydantic==1.5.1
89
pytest==5.4.2
910
pytest-cov==2.8.1
1011
pytest-mock==3.1.0

tests/test_custom_pretty.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
1+
import pytest
2+
13
from devtools import pformat
24

5+
try:
6+
import pydantic
7+
except ImportError:
8+
pydantic = None
9+
310

411
def test_simple():
512
class CustomCls:
@@ -62,4 +69,13 @@ def __pretty__(self, fmt, **kwargs):
6269
yield 'xxx'
6370

6471
assert pformat(Foobar()) == 'xxx'
65-
assert pformat(Foobar).endswith(".test_pretty_class.<locals>.Foobar'>")
72+
assert pformat(Foobar) == "<class 'tests.test_custom_pretty.test_pretty_class.<locals>.Foobar'>"
73+
74+
75+
@pytest.mark.skipif(pydantic is None, reason='numpy not installed')
76+
def test_pydantic_pretty():
77+
class MyModel(pydantic.BaseModel):
78+
foobar: int = 1
79+
80+
assert pformat(MyModel()) == 'MyModel(\n foobar=1,\n)'
81+
assert pformat(MyModel) == "<class 'tests.test_custom_pretty.test_pydantic_pretty.<locals>.MyModel'>"

0 commit comments

Comments
 (0)