Created
June 28, 2018 10:41
-
-
Save cypreess/7c112f33dc949ca2a7672f16fd72dd9b to your computer and use it in GitHub Desktop.
Pretty printer
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
def pprint(data, ident=2, start_ident=0, ident_char=' ', inside_dict=False, inside_list=False, line_length=80, | |
line_context=0): | |
if not inside_dict: | |
print(ident_char * start_ident, end='') | |
if len(repr(data)) + start_ident + line_context < line_length: | |
print(repr(data) + (',' if inside_dict or inside_list else '')) | |
return | |
elif isinstance(data, dict): | |
print('{') | |
for key in sorted(data.keys()): | |
string = "%s%s: " % (ident_char * (start_ident + ident), repr(key)) | |
print(string, end='') | |
pprint(data[key], ident=ident, start_ident=start_ident + ident, ident_char=ident_char, inside_dict=True, | |
line_length=line_length, line_context=len(string)) | |
print(ident_char * start_ident + '}' + (',' if inside_dict or inside_list else '')) | |
elif isinstance(data, set): | |
print('{') | |
for el in sorted(data): | |
pprint(el, ident=ident, start_ident=start_ident + ident, ident_char=ident_char, inside_list=True, | |
line_length=line_length) | |
print(ident_char * (ident + start_ident) + '}' + (',' if inside_dict or inside_list else '')) | |
elif isinstance(data, list): | |
print('[') | |
for el in data: | |
pprint(el, ident=ident, start_ident=start_ident + ident, ident_char=ident_char, inside_list=True, | |
line_length=line_length) | |
print(ident_char * (ident + start_ident) + ']' + (',' if inside_dict or inside_list else '')) | |
else: | |
print("%s" % repr(data) + (',' if inside_dict or inside_list else '')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment