hbutils.string.tree
- Overview:
Library for formatting trees.
This is a copy of https://github.com/jml/tree-format, with a few modifications, its based commit id is 4c6de1074d96129b7e03eecdf42fac2cde3b5151.
- Changes:
The
NEWLINEvalue is modified to empty string for the vision of final tree.The
print_treefunction is removed because it is nowhere to be used in our case.Add
__doc__forformat_treefunction.All the
\nstrings are replaced toos.linesep.The code is reformatted.
format_tree
- hbutils.string.tree.format_tree(node: Any, format_node: Callable[[Any], str], get_children: Callable[[Any], Iterable[Any]], encoding: str | None = None) str[source]
Format the given tree structure into a string representation with tree-like visual formatting.
- Parameters:
node (Any) – The root node of the tree to format.
format_node (Callable[[Any], str]) – Function that takes a node and returns its string representation.
get_children (Callable[[Any], Iterable[Any]]) – Function that takes a node and returns an iterable of its children.
encoding (str) – Encoding to be used. Default is
Nonewhich means system encoding. When ASCII encoding is used, ASCII chars will be used instead of UTF-8 box-drawing characters.
- Returns:
Formatted tree string with visual tree structure.
- Return type:
str
- Example::
>>> from operator import itemgetter >>> >>> from hbutils.string import format_tree >>> >>> tree = ( ... 'foo', [ ... ('bar', [ ... ('a', []), ... ('b', []), ... ]), ... ('baz', []), ... ('qux', [ ... ('c\nd', []), ... ]), ... ], ... ) >>> print(format_tree(tree, format_node=itemgetter(0), get_children=itemgetter(1))) foo ├── bar │ ├── a │ └── b ├── baz └── qux └── c d