Skip to content

Commit

Permalink
text_viz.py: Add to_repr() that shows a representation that can recre…
Browse files Browse the repository at this point in the history
…ate the tree.

This is another interesting representation of a Tree. It allows to
copy-paste the result and recreate the original tree, if used with
infinite depth and number of children.
  • Loading branch information
jordibc committed Mar 7, 2024
1 parent fe221d1 commit 2079347
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions ete4/core/text_viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,18 @@ def get_branches_repr(are_last, is_leaf, px):

return (prefix + ('└' if are_last[-1] else '├') +
'─' * px + ('╴' if is_leaf else '┐'))


def to_repr(tree, depth=4, nchildren=3):
"""Return a text representation that exactly recreates the tree.
If depth and nchildren are None, return the full representation.
"""
children = tree.children[:nchildren]
depth_1 = depth if depth is None else depth - 1
children_repr = '...' if depth == 0 else (
', '.join(to_repr(node, depth_1, nchildren) for node in children) +
('' if nchildren is None or len(tree.children) <= nchildren
else ', ...'))

return 'Tree(%r, [%s])' % (tree.props, children_repr)

0 comments on commit 2079347

Please sign in to comment.