Skip to content

fix __pretty__ get #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions devtools/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,22 @@ def str(self, highlight=False) -> str:
s = ''
if self.name:
s = sformat(self.name, sformat.blue, apply=highlight) + ': '
s += pformat(self.value, indent=4, highlight=highlight)
suffix = (
' ({0.value.__class__.__name__}) {1}'
.format(self, ' '.join('{}={}'.format(k, v) for k, v in self.extra))
.rstrip(' ') # trailing space if extra is empty

suffix = sformat(
' ({.value.__class__.__name__}){}'.format(self, ''.join(' {}={}'.format(k, v) for k, v in self.extra)),
sformat.dim,
apply=highlight
)
s += sformat(suffix, sformat.dim, apply=highlight)
try:
s += pformat(self.value, indent=4, highlight=highlight)
except Exception as exc:
s += '{!r}{}\n {}'.format(
self.value,
suffix,
sformat('!!! error pretty printing value: {!r}'.format(exc), sformat.yellow, apply=highlight),
)
else:
s += suffix
return s

def __str__(self) -> str:
Expand Down
6 changes: 5 additions & 1 deletion devtools/prettier.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import io
import os
import textwrap
import warnings
from collections import OrderedDict
from collections.abc import Generator
from typing import Any, Union
Expand Down Expand Up @@ -89,10 +90,13 @@ def _format(self, value: Any, indent_current: int, indent_first: bool):
self._stream.write(indent_current * self._c)

pretty_func = getattr(value, '__pretty__', None)
if pretty_func and not isinstance(value, MockCall):
if pretty_func and callable(pretty_func) and not isinstance(value, MockCall):
try:
gen = pretty_func(fmt=fmt, skip_exc=SkipPretty)
self._render_pretty(gen, indent_current)
except TypeError as e:
if e.args != ("__pretty__() missing 1 required positional argument: 'self'",):
raise
except SkipPretty:
pass
else:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_custom_pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,19 @@ def __pretty__(self, fmt, **kwargs):
my_cls = CustomCls()
v = pformat(my_cls)
assert v == "'xxx'123"


def test_pretty_not_func():
class Foobar:
__pretty__ = 1

assert '<locals>.Foobar object' in pformat(Foobar())


def test_pretty_class():
class Foobar:
def __pretty__(self, fmt, **kwargs):
yield 'xxx'

assert pformat(Foobar()) == 'xxx'
assert pformat(Foobar).endswith(".test_pretty_class.<locals>.Foobar'>")
17 changes: 17 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def test_small_call_frame_warning():
2,
3,
)
print(str(v))
assert re.sub(r':\d{2,}', ':<line no>', str(v)) == (
"tests/test_main.py:<line no> test_small_call_frame_warning "
"(error passing code, found <class '_ast.Tuple'> not Call)\n"
Expand Down Expand Up @@ -239,3 +240,19 @@ def test_starred_kwargs():
' foo: 1 (int)',
' bar: 2 (int)',
}


def test_pretty_error():
class BadPretty:
def __getattr__(self, item):
raise RuntimeError('this is an error')

b = BadPretty()
v = debug.format(b)
s = re.sub(r':\d{2,}', ':<line no>', str(v))
s = re.sub(r'0x[0-9a-f]+', '0x000', s)
assert s == (
"tests/test_main.py:<line no> test_pretty_error\n"
" b: <tests.test_main.test_pretty_error.<locals>.BadPretty object at 0x000> (BadPretty)\n"
" !!! error pretty printing value: RuntimeError('this is an error')"
)