Skip to content

Instantly share code, notes, and snippets.

@alaniwi
Last active July 31, 2020 14:50
Show Gist options
  • Save alaniwi/433bbf452ec8dc3d81069a9f9bcd051e to your computer and use it in GitHub Desktop.
Save alaniwi/433bbf452ec8dc3d81069a9f9bcd051e to your computer and use it in GitHub Desktop.
Commented pretty-printer
def commented_pprint(obj, name='obj', indent=4):
"""
Pretty-print object obj, which can contain nested dictionaries, lists and tuples,
with comment lines showing how to index it.
"""
pairs = list(_yield_pprint_lines(obj, name=name, indent=indent))
max_len = max(len(line) for line, _ in pairs)
for line, comment in pairs:
print(f'{line:{max_len}} {comment}')
def _yield_pprint_lines(obj, name, indent, _this_indent=0, _top=True, _prefix=''):
spaces = ' ' * _this_indent
items = None
is_dict = False
if isinstance(obj, dict):
chars = '{}'
items = obj.items()
is_dict = True
elif isinstance(obj, tuple):
chars = '()'
items = enumerate(obj)
elif isinstance(obj, list):
chars = '[]'
items = enumerate(obj)
comma = '' if _top else ','
if items is None:
yield (f'{spaces}{_prefix}{repr(obj)}{comma}', f'# {name}')
elif not obj:
yield (f'{spaces}{_prefix}{chars}{comma}', f'# {name}')
else:
yield (f'{spaces}{_prefix}{chars[0]}', '')
for k, v in items:
yield from _yield_pprint_lines(v,
name=f'{name}[{repr(k)}]',
indent=indent,
_this_indent=(_this_indent + indent + len(_prefix)),
_prefix=(f'{repr(k)}: ' if is_dict else ''),
_top=False)
yield (f"{spaces}{' ' * len(_prefix)}{chars[1]}{comma}", f'# {name}')
if __name__ == '__main__':
a = { 'blah': ['foo', {'bar': 'baz', 'qux': 4}, 4, [], ['x', 6]], 'quux': [(3, 5), 's'] }
commented_pprint(a, name='a')
# PRINTS:
#
# {
# 'blah': [
# 'foo', # a['blah'][0]
# {
# 'bar': 'baz', # a['blah'][1]['bar']
# 'qux': 4, # a['blah'][1]['qux']
# }, # a['blah'][1]
# 4, # a['blah'][2]
# [], # a['blah'][3]
# [
# 'x', # a['blah'][4][0]
# 6, # a['blah'][4][1]
# ], # a['blah'][4]
# ], # a['blah']
# 'quux': [
# (
# 3, # a['quux'][0][0]
# 5, # a['quux'][0][1]
# ), # a['quux'][0]
# 's', # a['quux'][1]
# ], # a['quux']
# } # a
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment