Created
July 5, 2015 19:00
-
-
Save zas/3234e723ddd4e3ee3be0 to your computer and use it in GitHub Desktop.
Pretty instance/dict/list/etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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