Last active
March 18, 2018 10:47
-
-
Save milesrout/315e2e94b9c189405b7ccc97462673c4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 to_sexpr(o, indent=None): | |
return fmt_sexpr(json.loads(MyJSONEncoder().encode(o))) | |
def fmt_sexpr(o, depth=1): | |
if isinstance(o, dict): | |
return fmt_sexpr(list(o.values()), depth) | |
if isinstance(o, tuple): | |
return fmt_sexpr(list(o), depth) | |
if isinstance(o, list): | |
if len(o) == 0: | |
return '()' | |
if len(o) == 1: | |
return fmt_sexpr(o[0], depth) | |
return fmt_sexpr_list(o, depth) | |
return str(o) | |
@compose(''.join) | |
def fmt_sexpr_list_long(o, depth): | |
yield '(' | |
yield fmt_sexpr(o[0], depth + 1) | |
for item in o[1:]: | |
yield '\n' | |
yield (2 * depth * ' ') | |
yield fmt_sexpr(item, depth + 1) | |
yield ')' | |
@compose(''.join) | |
def fmt_sexpr_list_short(o, depth): | |
yield '(' | |
yield fmt_sexpr(o[0], depth) | |
for item in o[1:]: | |
yield ' ' | |
yield fmt_sexpr(item, depth) | |
yield ')' | |
def fmt_sexpr_list(o, depth): | |
result = fmt_sexpr_list_short(o, depth) | |
if max(map(len, result.splitlines())) > 80: | |
return fmt_sexpr_list_long(o, depth) | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment