Skip to content

Commit

Permalink
implement pretty printing helper for the stdlib pprint module
Browse files Browse the repository at this point in the history
...using a not-so-nice hack that only works for python 3.5+.
  • Loading branch information
wbolster committed Jun 30, 2017
1 parent d8027c8 commit 55c0303
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/sanest/sanest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import collections
import collections.abc
import copy
import pprint
import reprlib
import sys

Expand Down Expand Up @@ -435,6 +436,31 @@ def copy(self, *, deep=False):
return fn(self)


def pprint_sanest_collection(
self, object, stream, indent, allowance, context, level):
"""
Pretty-printing helper for use by the built-in pprint module.
"""
opening = '{}.{.__name__}('.format(__package__, type(object))
stream.write(opening)
if type(object._data) is builtins.dict:
f = self._pprint_dict
else:
f = self._pprint_list
f(object._data, stream, indent + len(opening), allowance, context, level)
stream.write(')')


# This is a hack that changes the internals of the pprint module,
# which has no public API to register custom formatter routines.
try:
dispatch_table = pprint.PrettyPrinter._dispatch
except Exception: # pragma: no cover
pass # Python 3.4 and older do not have a dispatch table.
else:
dispatch_table[SaneCollection.__repr__] = pprint_sanest_collection


class dict(SaneCollection, collections.abc.MutableMapping):
"""
dict-like container with support for nested lookups and type checking.
Expand Down
23 changes: 23 additions & 0 deletions test_sanest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import builtins
import copy
import pickle
import pprint
import sys
import textwrap

import pytest

Expand Down Expand Up @@ -1626,3 +1628,24 @@ def test_wrong_path_for_container_type():
def test_missing_arg_repr():
assert repr(_sanest.MISSING) == '<missing>'
assert str(_sanest.MISSING) == '<missing>'


@pytest.mark.skipif(
sys.version_info < (3, 5),
reason="requires python 3.5+ pprint module")
def test_pretty_printing_pprint():
d = sanest.dict(a='a' * 30, b='b' * 30)
expected = textwrap.dedent("""\
sanest.dict({'a': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'b': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'})
""").rstrip()
actual = pprint.pformat(d)
assert actual == expected

l = sanest.list(['a' * 30, 'b' * 30])
expected = textwrap.dedent("""\
sanest.list(['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'])
""").rstrip()
actual = pprint.pformat(l)
assert actual == expected

0 comments on commit 55c0303

Please sign in to comment.