Skip to content

Instantly share code, notes, and snippets.

@zas
Created July 5, 2015 19:00
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 zas/3234e723ddd4e3ee3be0 to your computer and use it in GitHub Desktop.
Save zas/3234e723ddd4e3ee3be0 to your computer and use it in GitHub Desktop.
Pretty instance/dict/list/etc
# -*- coding: utf-8 -*-
def pretty(value, ind=' ', eol='\n', level=0):
"""Return a pretty representation of an object"""
linesuffix = eol + ind * level
lineprefix = linesuffix + ind
level += 1
if hasattr(value, '__class__') and '__dict__' in dir(value):
value = value.__dict__
if isinstance(value, dict):
items = [
lineprefix +
repr(key) + ': ' + pretty(value[key], ind, eol, level)
for key in value
]
return '{%s}' % (','.join(items) + linesuffix)
elif isinstance(value, list):
items = [
lineprefix + pretty(item, ind, eol, level)
for item in value
]
return '[%s]' % (','.join(items) + linesuffix)
elif isinstance(value, tuple):
items = [
lineprefix + pretty(item, ind, eol, level)
for item in value
]
return '(%s)' % (','.join(items) + linesuffix)
else:
return repr(value)
if __name__ == '__main__':
d = {'a': 1, 'b': 'abc', 'c':
{'d': 4, 'e': (4, 5, 6)}, 'f': [{'g': 9}, 1.23]}
print pretty(d)
class test(object):
def __init__(self):
self.x = d
t = test()
print pretty(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment