Skip to content

Instantly share code, notes, and snippets.

@krosaen
Last active April 4, 2019 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krosaen/4d44023070f1dc3e2b9afc7df20d9ace to your computer and use it in GitHub Desktop.
Save krosaen/4d44023070f1dc3e2b9afc7df20d9ace to your computer and use it in GitHub Desktop.
def pretty_data(d):
return '\n'.join(data_lines(d))
def data_lines(d, prefix='', last=True, add_bookends=True):
def ground(d):
return isinstance(d, (str, float, int)) or ground_list(d) or ground_dict(d)
def ground_list(d):
return isinstance(d, list) and len(d) < 6 and all([isinstance(el, (str, float, int)) for el in d])
def ground_dict(d):
return isinstance(d, dict) and len(d) == 0
def format_ground(el):
if isinstance(el, int):
return str(el)
if isinstance(el, float):
return '{:.2f}'.format(el)
if isinstance(el, str):
return "'{}'".format(el)
if ground_list(el):
return '[{}]'.format(', '.join(map(format_ground, el)))
if ground_dict(el):
return '{}'
assert False, 'expected {} to be ground type'.format(el)
if ground(d):
return ['{}{}'.format(prefix, format_ground(d))]
if isinstance(d, list):
result = ['{}['.format(prefix)] if add_bookends else []
child_prefix = prefix + 2*' '# if add_bookends else prefix
last_i = len(d) - 1
for idx, el in enumerate(d):
last_child = idx == last_i
result.extend(data_lines(el, child_prefix, last=last_child))
postfix = '' if last else ','
if add_bookends:
result.append('{}]{}'.format(prefix, postfix))
return result
if isinstance(d, dict):
result = ['{}{{'.format(prefix)] if add_bookends else []
key_prefix = prefix + 2 * ' '
last_i = len(d) - 1
for idx, (k, v) in enumerate(d.items()):
last_child = idx == last_i
if ground(v):
result.append('{}{}: {},'.format(key_prefix, format_ground(k), format_ground(v)))
else:
if isinstance(v, dict):
result.append('{}{}: {{'.format(key_prefix, format_ground(k)))
elif isinstance(v, list):
result.append('{}{}: ['.format(key_prefix, format_ground(k)))
val_prefix = key_prefix + 2 * ' ' if add_bookends else key_prefix
result.extend(data_lines(v, val_prefix, last=last_child, add_bookends=False))
postfix = '' if last_child else ','
if isinstance(v, dict):
result.append('{}}}{}'.format(key_prefix, postfix))
elif isinstance(v, list):
result.append('{}]{}'.format(key_prefix, postfix))
postfix = '' if last else ','
if add_bookends:
result.append('{}}}{}'.format(prefix, postfix))
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment