How to Display a treelib Tree Using ASCII Representation
To display a treelib tree using ASCII representation, call the Tree.show() method with the line_type parameter set to "ascii" for simple pipes and dashes, or use "ascii-ex" (default) for Unicode box-drawing characters.
The treelib library (caesar0301/treelib) provides a lightweight Python implementation for managing tree data structures. When you need to visualize hierarchy during debugging or reporting, the Tree class offers built-in ASCII formatting through the show() method defined in treelib/tree.py.
Understanding the Tree.show() Method
The visualization logic resides in the Tree.show() method at line 31 of treelib/tree.py. When invoked, show() delegates to a private routine __print_backend(), which traverses the tree breadth-first, constructs a formatted line for every node, and either prints to stdout or returns the result as a string.
The core ASCII generation relies on helper utilities in treelib/misc.py, specifically the _get_line_type function, which maps symbolic style names to the actual connector characters used for branches.
ASCII Line Types Available
The appearance of your tree is controlled by the line_type argument passed to show(). The library supports multiple visual styles ranging from pure ASCII to Unicode box-drawing characters:
ascii— Simple ASCII connectors using|--and`--for branches. Ideal for environments without Unicode support.ascii-ex— Extended ASCII using Unicode box-drawing characters├──and└──. This is the default style whenline_typeis omitted.ascii-em— Double-line Unicode style using╠══and╚══for emphasis.ascii-emr— Rounded-corner Unicode connectors.ascii-emv— Mixed vertical Unicode style.ascii-emh— Mixed horizontal Unicode style.
Practical Code Examples
Basic ASCII Tree
The following example creates a simple hierarchy and renders it using pure ASCII characters:
from treelib import Tree
tree = Tree()
tree.create_node("Root", "root")
tree.create_node("Child A", "a", parent="root")
tree.create_node("Child B", "b", parent="root")
tree.create_node("Grandchild", "gc", parent="a")
# Pure ASCII style (pipes and dashes)
tree.show(line_type="ascii")
Output:
Root
|-- Child A
| `-- Grandchild
`-- Child B
Unicode Box-Drawing Styles
To use the default Unicode style or double-line variants:
# Default unicode style (ascii-ex)
tree.show()
# Double-line emphasis style
tree.show(line_type="ascii-em")
Output for ascii-em:
Root
╠══ Child A
║ ╚══ Grandchild
╚══ Child B
Capturing Output as String
By default, show() prints to stdout. To capture the formatted tree as a string for logging or file writing, set stdout=False:
ascii_tree = tree.show(line_type="ascii", stdout=False)
with open("tree_output.txt", "w") as f:
f.write(ascii_tree)
Customizing the Display
Beyond line styles, Tree.show() accepts several parameters defined in treelib/tree.py to control output:
idhidden— Set toFalseto display node identifiers (e.g.,Root[root]). Default isTrue.key— Pass a lambda function to sort nodes at each level (e.g.,key=lambda x: x.tag).reverse— Boolean to reverse the sort order whenkeyis provided.filter— Function to exclude specific nodes from the display.data_property— Display a specific attribute from the node's data field instead of the tag.
For comprehensive examples of these filters and sorting options, refer to examples/getting_started.py in the repository.
Summary
- The
treeliblibrary renders trees viaTree.show()intreelib/tree.py, which delegates to__print_backend(). - Use
line_type="ascii"for pure ASCII output with|--connectors, orline_type="ascii-ex"(default) for Unicode box-drawing characters. - Additional styles include
ascii-em,ascii-emr,ascii-emv, andascii-emhfor various Unicode visual effects. - Set
stdout=Falseto capture the formatted string instead of printing directly to the console. - Customize output with
idhidden,key,filter, anddata_propertyparameters.
Frequently Asked Questions
How do I get pure ASCII output without Unicode characters?
Pass line_type="ascii" to the show() method. This uses simple pipe and dash characters (|-- and `--) instead of Unicode box-drawing symbols, ensuring compatibility with terminals that do not support UTF-8.
Can I save the tree visualization to a file instead of printing it?
Yes. Set the stdout parameter to False when calling show(). This returns the formatted tree as a string, which you can then write to a file using standard Python file operations.
What is the difference between ascii-ex and ascii-em line types?
The ascii-ex style (default) uses standard Unicode box-drawing characters with single lines (├── and └──). The ascii-em style uses double-line Unicode characters (╠══ and ╚══) for a more prominent, emphasized visual hierarchy.
How can I display node IDs alongside node tags in the tree?
Set idhidden=False when calling show(). This appends the node identifier in brackets after each tag (e.g., Root[root]), which is useful for debugging or when you need to reference specific node IDs programmatically.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →