hbutils.string.tree

Tree formatting utilities.

This module provides helper utilities for formatting arbitrary tree structures into a text-based representation using Unicode box-drawing characters or ASCII fallback characters. The core public API is format_tree(), which accepts custom formatting and child-fetching callbacks to support a wide range of data structures.

The module is a modified variant of jml/tree-format with the following changes:

  • The newline character used in the internal formatting is an empty string to match the expected final tree output format.

  • The original print_tree helper is removed.

  • \n strings are replaced with os.linesep to respect the host operating system’s line separator.

  • Code is reformatted for readability.

The module contains the following main component:

  • format_tree() - Format a tree structure into a human-readable string.

Example:

>>> from operator import itemgetter
>>> from hbutils.string.tree import format_tree
>>>
>>> tree = (
...     'root', [
...         ('child', []),
...         ('branch', [
...             ('leaf', []),
...         ]),
...     ],
... )
>>> print(format_tree(tree, format_node=itemgetter(0), get_children=itemgetter(1)))
root
├── child
└── branch
    └── leaf

Note

The format_tree() function uses UTF-8 box-drawing characters by default and falls back to ASCII characters if the encoding indicates ASCII usage.

__all__

hbutils.string.tree.__all__ = ['format_tree']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

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, optional) – Encoding to be used. Default is None which 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