Skip to content

Instantly share code, notes, and snippets.

@samueljohn
Created April 29, 2014 17:55
Show Gist options
  • Save samueljohn/11407488 to your computer and use it in GitHub Desktop.
Save samueljohn/11407488 to your computer and use it in GitHub Desktop.
Print a nice text tree of nested python objects.
def print_tree(tree, prefix=[], last_prefix="", print_item=str):
"""
Return a string where each line represents one item of tree.
prefix and last_prefix are used internally.
print_item:
The function applied to items in the tree.
Default `str`.
Example:
>>> print(print_tree(['f', [2, [22, 33], 3]]))
['f', [2, [22, 33], 3]]
├── 'f'
└── [2, [22, 33], 3]
├── 2
├── [22, 33]
│ ├── 22
│ └── 33
└── 3
"""
s = "\n" + "".join(prefix[:-1]) + last_prefix + print_item(tree)
try:
last_i = len(tree) - 1
if tree is tree[0]:
return s # avoid infinit recursion
for i, item in enumerate(tree):
if i == last_i:
s += print_tree(item,
prefix=prefix + [" "],
last_prefix="└── ",
print_item=print_item)
else:
s += print_tree(item,
prefix=prefix + ["│ "],
last_prefix="├── ",
print_item=print_item)
except TypeError:
pass
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment