from pathlib import Path from typing import Any from unittest.mock import patch from ansi2html import Ansi2HTMLConverter from devtools import PrettyFormat THIS_DIR = Path(__file__).parent DOCS_DIR = (THIS_DIR / '..').resolve() EXAMPLES_DIR = DOCS_DIR / 'examples' TMP_EXAMPLES_DIR = DOCS_DIR / '.tmp_examples' MAX_LINE_LENGTH = int( re.search(r'max_line_length = (\d+)', (EXAMPLES_DIR / '.editorconfig').read_text()).group(1)) LONG_LINE = 50 pformat = PrettyFormat(simple_cutoff=LONG_LINE) def to_string(value: Any) -> str: # attempt to build a pretty equivalent of the print output if isinstance(value, (dict, list, tuple, set)): return pformat(value) elif isinstance(value, str) and any( re.fullmatch(r, value, flags=re.DOTALL) for r in ['{".+}', r'\[.+\]']): try: obj = json.loads(value) except ValueError: # not JSON, not a problem pass else:
v = { 'foo': { 'whatever': [3, 2, 1] }, 'sentence': 'hello\nworld', 'generator': (i * 2 for i in [1, 2, 3]), 'matrix': np.matrix([[1, 2, 3, 4], [50, 60, 70, 80], [900, 1000, 1100, 1200], [13000, 14000, 15000, 16000]]) } # pretty print of v pprint(v) # as above without colours, the generator will also be empty as it's already been evaluated s = pformat(v, highlight=False) print(s) pp = PrettyFormat( indent_step=2, # default: 4 indent_char='.', # default: space repr_strings=True, # default: False simple_cutoff= 2, # default: 10 (if repr is below this length it'll be shown on one line) width=80, # default: 120 yield_from_generators=False # default: True (whether to evaluate generators) ) print(pp(v, highlight=True))