Skip to content

Instantly share code, notes, and snippets.

@jjl
Last active December 21, 2015 06:09
Show Gist options
  • Save jjl/6261928 to your computer and use it in GitHub Desktop.
Save jjl/6261928 to your computer and use it in GitHub Desktop.
Print the shapes of nested data structures
def printshape(x):
children = lambda a: { printshape(b) for b in a }
fmt = lambda a,b: a.format("|".join(b))
together = lambda a,b: fmt(a, children(b))
if isinstance(x, list):
return together("list[{}]", x)
elif isinstance(x, set):
return together("set[{}]", x)
elif isinstance(x, tuple):
return together("tuple[{}]", x)
elif isinstance(x, dict):
return together("dict[{}]", x.values())
elif isinstance(x, (str,unicode)):
return "string"
elif isinstance(x, int):
return "int"
elif isinstance(x, float):
return "float"
elif isinstance(x, file):
return "file"
else:
return x.__class__.__name__
# Helper for printshape_i
def _print_container(name, children, depth=0):
indent_to = lambda a,b: "".join(["".ljust(4*a),b])
if len(children) > 1:
return "\n".join(["{}[".format(name),"\n".join(map(lambda k: indent_to(depth+1,k), children)), indent_to(depth,"]")])
elif len(children) == 1:
return "{}[{}]".format(name, "".join(children))
else:
return "{}[]".format(name)
# Prints out the shape in a more indented fashion. Useful for huge data structures
def printshape_i(x, depth=0):
children = lambda a: { printshape_i(b,depth+1) for b in a }
indent_to = lambda a,b: "".join(["".ljust(4*a),b])
container = lambda a,b: _print_container(a, children(b), depth)
if isinstance(x, list):
return container("list", x)
elif isinstance(x, set):
return container("set", x)
elif isinstance(x, tuple):
return container("tuple", x)
elif isinstance(x, dict):
return container("dict", x.values())
elif isinstance(x, (str,unicode)):
return "string"
elif isinstance(x, int):
return "int"
elif isinstance(x, float):
return "float"
elif isinstance(x, file):
return "file"
else:
return x.__class__.__name__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment