bigtree

πŸ”¨ ExportΒΆ

Export Tree to list, dictionary, and pandas DataFrame.

Tree Export MethodsΒΆ

Export Tree to

Method

Command Line / Others

print_tree, yield_tree

Dictionary

tree_to_dict, tree_to_nested_dict

DataFrame

tree_to_dataframe

Dot (for .dot, .png, .svg, .jpeg, etc.)

tree_to_dot

Pillow (for .png, .jpg, .jpeg, etc.)

tree_to_pillow

Mermaid Markdown (for .md)

tree_to_mermaid

While exporting to another data type, methods can take in arguments to determine what information to extract.

Tree Export CustomizationsΒΆ

Method

Extract node attributes

Specify maximum depth

Skip depth

Extract leaves only

Others

print_tree

Yes with attr_list or all_attrs

Yes with max_depth

No, but can specify subtree

No

Tree style

yield_tree

No, returns node

Yes with max_depth

No, but can specify subtree

No

Tree style

tree_to_dict

Yes with attr_dict or all_attrs

Yes with max_depth

Yes with skip_depth

Yes with leaf_only

Dict key for parent

tree_to_nested_dict

Yes with attr_dict or all_attrs

Yes with max_depth

No

No

Dict key for node name and node children

tree_to_dataframe

Yes with attr_dict or all_attrs

Yes with max_depth

Yes with skip_depth

Yes with leaf_only

Column name for path, node name, node parent

tree_to_dot

No

No

No

No

Graph attributes, background, node, edge colour, etc.

tree_to_pillow

No

Yes, using keyword arguments similar to yield_tree

No

No

Font (family, size, colour), background colour, etc.

tree_to_mermaid

No

Yes, using keyword arguments similar to yield_tree

No

No

Node shape, node fill, edge arrow, edge label etc.

Functions:

print_tree(tree[,Β node_name_or_path,Β ...])

Print tree to console, starting from tree.

tree_to_dataframe(tree[,Β path_col,Β ...])

Export tree to pandas DataFrame.

tree_to_dict(tree[,Β name_key,Β parent_key,Β ...])

Export tree to dictionary.

tree_to_dot(tree[,Β directed,Β rankdir,Β ...])

Export tree or list of trees to image.

tree_to_mermaid(tree[,Β title,Β rankdir,Β ...])

Export tree to mermaid Markdown text.

tree_to_nested_dict(tree[,Β name_key,Β ...])

Export tree to nested dictionary.

tree_to_pillow(tree[,Β width,Β height,Β ...])

Export tree to image (JPG, PNG).

yield_tree(tree[,Β node_name_or_path,Β ...])

Generator method for customizing printing of tree, starting from tree.

bigtree.tree.export.print_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, all_attrs: bool = False, attr_list: Iterable[str] = [], attr_omit_null: bool = False, attr_bracket: List[str] = ['[', ']'], style: str = 'const', custom_style: Iterable[str] = []) NoneΒΆ

Print tree to console, starting from tree.

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path

  • Able to customize for maximum depth to print, using max_depth

  • Able to choose which attributes to show or show all attributes, using attr_name_filter and all_attrs

  • Able to omit showing of attributes if it is null, using attr_omit_null

  • Able to customize open and close brackets if attributes are shown, using attr_bracket

  • Able to customize style, to choose from ansi, ascii, const, rounded, double, and custom style
    • Default style is const style

    • If style is set to custom, user can choose their own style for stem, branch and final stem icons

    • Stem, branch, and final stem symbol should have the same number of characters

Printing tree

>>> from bigtree import Node, print_tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> print_tree(root)
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c

Printing Sub-tree

>>> print_tree(root, node_name_or_path="b")
b
β”œβ”€β”€ d
└── e
>>> print_tree(root, max_depth=2)
a
β”œβ”€β”€ b
└── c

Printing Attributes

>>> print_tree(root, attr_list=["age"])
a [age=90]
β”œβ”€β”€ b [age=65]
β”‚   β”œβ”€β”€ d [age=40]
β”‚   └── e [age=35]
└── c [age=60]
>>> print_tree(root, attr_list=["age"], attr_bracket=["*(", ")"])
a *(age=90)
β”œβ”€β”€ b *(age=65)
β”‚   β”œβ”€β”€ d *(age=40)
β”‚   └── e *(age=35)
└── c *(age=60)

Available Styles

>>> print_tree(root, style="ansi")
a
|-- b
|   |-- d
|   `-- e
`-- c
>>> print_tree(root, style="ascii")
a
|-- b
|   |-- d
|   +-- e
+-- c
>>> print_tree(root, style="const")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c
>>> print_tree(root, style="const_bold")
a
┣━━ b
┃   ┣━━ d
┃   ┗━━ e
┗━━ c
>>> print_tree(root, style="rounded")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   ╰── e
╰── c
>>> print_tree(root, style="double")
a
╠══ b
β•‘   ╠══ d
β•‘   β•šβ•β• e
β•šβ•β• c
Parameters:
  • tree (Node) – tree to print

  • node_name_or_path (str) – node to print from, becomes the root node of printing

  • max_depth (int) – maximum depth of tree to print, based on depth attribute, optional

  • all_attrs (bool) – indicator to show all attributes, defaults to False, overrides attr_list and attr_omit_null

  • attr_list (Iterable[str]) – list of node attributes to print, optional

  • attr_omit_null (bool) – indicator whether to omit showing of null attributes, defaults to False

  • attr_bracket (List[str]) – open and close bracket for all_attrs or attr_list

  • style (str) – style of print, defaults to abstract style

  • custom_style (Iterable[str]) – style of stem, branch and final stem, used when style is set to β€˜custom’

bigtree.tree.export.tree_to_dataframe(tree: T, path_col: str = 'path', name_col: str = 'name', parent_col: str = '', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0, skip_depth: int = 0, leaf_only: bool = False) DataFrameΒΆ

Export tree to pandas DataFrame.

All descendants from tree will be exported, tree can be the root node or child node of tree.

>>> from bigtree import Node, tree_to_dataframe
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree_to_dataframe(root, name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
     path name parent  person age
0      /a    a   None          90
1    /a/b    b      a          65
2  /a/b/d    d      b          40
3  /a/b/e    e      b          35
4    /a/c    c      a          60

For a subset of a tree.

>>> tree_to_dataframe(b, name_col="name", parent_col="parent", path_col="path", attr_dict={"age": "person age"})
     path name parent  person age
0    /a/b    b      a          65
1  /a/b/d    d      b          40
2  /a/b/e    e      b          35
Parameters:
  • tree (Node) – tree to be exported

  • path_col (str) – column name for node.path_name, defaults to β€˜path’

  • name_col (str) – column name for node.node_name, defaults to β€˜name’

  • parent_col (str) – column name for node.parent.node_name, optional

  • attr_dict (Dict[str, str]) – dictionary mapping node attributes to column name, key: node attributes, value: corresponding column in dataframe, optional

  • all_attrs (bool) – indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

  • max_depth (int) – maximum depth to export tree, optional

  • skip_depth (int) – number of initial depths to skip, optional

  • leaf_only (bool) – indicator to retrieve only information from leaf nodes

Returns:

(pd.DataFrame)

bigtree.tree.export.tree_to_dict(tree: T, name_key: str = 'name', parent_key: str = '', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0, skip_depth: int = 0, leaf_only: bool = False) Dict[str, Any]ΒΆ

Export tree to dictionary.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Exported dictionary will have key as node path, and node attributes as a nested dictionary.

>>> from bigtree import Node, tree_to_dict
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree_to_dict(root, name_key="name", parent_key="parent", attr_dict={"age": "person age"})
{'/a': {'name': 'a', 'parent': None, 'person age': 90}, '/a/b': {'name': 'b', 'parent': 'a', 'person age': 65}, '/a/b/d': {'name': 'd', 'parent': 'b', 'person age': 40}, '/a/b/e': {'name': 'e', 'parent': 'b', 'person age': 35}, '/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}

For a subset of a tree

>>> tree_to_dict(c, name_key="name", parent_key="parent", attr_dict={"age": "person age"})
{'/a/c': {'name': 'c', 'parent': 'a', 'person age': 60}}
Parameters:
  • tree (Node) – tree to be exported

  • name_key (str) – dictionary key for node.node_name, defaults to β€˜name’

  • parent_key (str) – dictionary key for node.parent.node_name, optional

  • attr_dict (Dict[str, str]) – dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional

  • all_attrs (bool) – indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

  • max_depth (int) – maximum depth to export tree, optional

  • skip_depth (int) – number of initial depths to skip, optional

  • leaf_only (bool) – indicator to retrieve only information from leaf nodes

Returns:

(Dict[str, Any])

bigtree.tree.export.tree_to_dot(tree: T | List[T], directed: bool = True, rankdir: str = 'TB', bg_colour: str = '', node_colour: str = '', node_shape: str = '', edge_colour: str = '', node_attr: Callable[[T], Dict[str, Any]] | str = '', edge_attr: Callable[[T], Dict[str, Any]] | str = '') pydot.DotΒΆ

Export tree or list of trees to image. Possible node attributes include style, fillcolor, shape.

>>> from bigtree import Node, tree_to_dot
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> graph = tree_to_dot(root)

Display image directly without saving (requires IPython)

>>> from IPython.display import Image, display
>>> plt = Image(graph.create_png())
>>> display(plt)
<IPython.core.display.Image object>

Export to image, dot file, etc.

>>> graph.write_png("assets/docstr/tree.png")
>>> graph.write_dot("assets/docstr/tree.dot")

Export to string

>>> graph.to_string()
'strict digraph G {\nrankdir=TB;\na0 [label=a];\nb0 [label=b];\na0 -> b0;\nd0 [label=d];\nb0 -> d0;\ne0 [label=e];\nb0 -> e0;\nc0 [label=c];\na0 -> c0;\n}\n'

Defining node and edge attributes (using node attribute)

>>> class CustomNode(Node):
...     def __init__(self, name, node_shape="", edge_label="", **kwargs):
...         super().__init__(name, **kwargs)
...         self.node_shape = node_shape
...         self.edge_label = edge_label
...
...     @property
...     def edge_attr(self):
...         if self.edge_label:
...             return {"label": self.edge_label}
...         return {}
...
...     @property
...     def node_attr(self):
...         if self.node_shape:
...             return {"shape": self.node_shape}
...         return {}
>>>
>>>
>>> root = CustomNode("a", node_shape="circle")
>>> b = CustomNode("b", edge_label="child", parent=root)
>>> c = CustomNode("c", edge_label="child", parent=root)
>>> d = CustomNode("d", node_shape="square", edge_label="child", parent=b)
>>> e = CustomNode("e", node_shape="square", edge_label="child", parent=b)
>>> graph = tree_to_dot(root, node_colour="gold", node_shape="diamond", node_attr="node_attr", edge_attr="edge_attr")
>>> graph.write_png("assets/export_tree_dot.png")
https://github.com/kayjan/bigtree/raw/master/assets/export_tree_dot.png

Alternative way to define node and edge attributes (using callable function)

>>> def get_node_attribute(node: Node):
...     if node.is_leaf:
...         return {"shape": "square"}
...     return {"shape": "circle"}
>>>
>>>
>>> root = CustomNode("a")
>>> b = CustomNode("b", parent=root)
>>> c = CustomNode("c", parent=root)
>>> d = CustomNode("d", parent=b)
>>> e = CustomNode("e", parent=b)
>>> graph = tree_to_dot(root, node_colour="gold", node_attr=get_node_attribute)
>>> graph.write_png("assets/export_tree_dot_callable.png")
https://github.com/kayjan/bigtree/raw/master/assets/export_tree_dot_callable.png
Parameters:
  • tree (Node/List[Node]) – tree or list of trees to be exported

  • directed (bool) – indicator whether graph should be directed or undirected, defaults to True

  • rankdir (str) – layout direction, defaults to β€˜TB’ (top to bottom), can be β€˜BT’ (bottom to top), β€˜LR’ (left to right), β€˜RL’ (right to left)

  • bg_colour (str) – background color of image, defaults to None

  • node_colour (str) – fill colour of nodes, defaults to None

  • node_shape (str) – shape of nodes, defaults to None Possible node_shape include β€œcircle”, β€œsquare”, β€œdiamond”, β€œtriangle”

  • edge_colour (str) – colour of edges, defaults to None

  • node_attr (str | Callable) – If string type, it refers to Node attribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour and node_shape and defaults to None. Possible node styles include {β€œstyle”: β€œfilled”, β€œfillcolor”: β€œgold”, β€œshape”: β€œdiamond”}

  • edge_attr (str | Callable) – If stirng type, it refers to Node attribute for edge style. If callable type, it takes in the node itself and returns the edge style. This overrides edge_colour, and defaults to None. Possible edge styles include {β€œstyle”: β€œbold”, β€œlabel”: β€œedge label”, β€œcolor”: β€œblack”}

Returns:

(pydot.Dot)

bigtree.tree.export.tree_to_mermaid(tree: T, title: str = '', rankdir: str = 'TB', line_shape: str = 'basis', node_colour: str = '', node_border_colour: str = '', node_border_width: float = 1, node_shape: str = 'rounded_edge', node_shape_attr: Callable[[T], str] | str = '', edge_arrow: str = 'normal', edge_arrow_attr: Callable[[T], str] | str = '', edge_label: str = '', node_attr: Callable[[T], str] | str = '', **kwargs: Any) strΒΆ

Export tree to mermaid Markdown text. Accepts additional keyword arguments as input to yield_tree

Parameters for customizations that applies to entire flowchart include
  • Title, title

  • Layout direction, rankdir

  • Line shape or curvature, line_shape

  • Fill colour of nodes, node_colour

  • Border colour of nodes, node_border_colour

  • Border width of nodes, node_border_width

  • Node shape, node_shape

  • Edge arrow style, edge_arrow

Parameters for customizations that apply to customized nodes
  • Fill colour of nodes, fill under node_attr

  • Border colour of nodes, stroke under node_attr

  • Border width of nodes, stroke-width under node_attr

  • Node shape, node_shape_attr

  • Edge arrow style, edge_arrow_attr

  • Edge label, edge_label

Accepted Parameter Values

Possible rankdir
  • TB: top-to-bottom

  • BT: bottom-to-top

  • LR: left-to-right

  • RL: right-to-left

Possible line_shape
  • basis

  • bumpX: used in LR or RL direction

  • bumpY

  • cardinal: undirected

  • catmullRom: undirected

  • linear:

  • monotoneX: used in LR or RL direction

  • monotoneY

  • natural

  • step: used in LR or RL direction

  • stepAfter

  • stepBefore: used in LR or RL direction

Possible node_shape
  • rounded_edge: rectangular with rounded edges

  • stadium: (_) shape, rectangular with rounded ends

  • subroutine: ||_|| shape, rectangular with additional line at the ends

  • cylindrical: database node

  • circle: circular

  • asymmetric: >_| shape

  • rhombus: decision node

  • hexagon: <_> shape

  • parallelogram: /_/ shape

  • parallelogram_alt: \_\ shape, inverted parallelogram

  • trapezoid: /_\ shape

  • trapezoid_alt: \_/ shape, inverted trapezoid

  • double_circle

Possible edge_arrow
  • normal: directed arrow, shaded arrowhead

  • bold: bold directed arrow

  • dotted: dotted directed arrow

  • open: line, undirected arrow

  • bold_open: bold line

  • dotted_open: dotted line

  • invisible: no line

  • circle: directed arrow with filled circle arrowhead

  • cross: directed arrow with cross arrowhead

  • double_normal: bidirectional directed arrow

  • double_circle: bidirectional directed arrow with filled circle arrowhead

  • double_cross: bidirectional directed arrow with cross arrowhead

Refer to mermaid documentation for more information. Paste the output into any markdown file renderer to view the flowchart, alternatively visit the mermaid playground here.

Note

Advanced mermaid flowchart functionalities such as subgraphs and interactions (script, click) are not supported.

>>> from bigtree import tree_to_mermaid
>>> root = Node("a", node_shape="rhombus")
>>> b = Node("b", edge_arrow="bold", edge_label="Child 1", parent=root)
>>> c = Node("c", edge_arrow="dotted", edge_label="Child 2", parent=root)
>>> d = Node("d", node_style="fill:yellow, stroke:black", parent=b)
>>> e = Node("e", parent=b)
>>> graph = tree_to_mermaid(root)
>>> print(graph)
```mermaid
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%
flowchart TB
0("a") --> 0-0("b")
0-0 --> 0-0-0("d")
0-0 --> 0-0-1("e")
0("a") --> 0-1("c")
classDef default stroke-width:1
```

Customize node shape, edge label, edge arrow, and custom node attributes

>>> graph = tree_to_mermaid(root, node_shape_attr="node_shape", edge_label="edge_label", edge_arrow_attr="edge_arrow", node_attr="node_style")
>>> print(graph)
```mermaid
%%{ init: { 'flowchart': { 'curve': 'basis' } } }%%
flowchart TB
0{"a"} ==>|Child 1| 0-0("b")
0-0:::class0-0-0 --> 0-0-0("d")
0-0 --> 0-0-1("e")
0{"a"} -.->|Child 2| 0-1("c")
classDef default stroke-width:1
classDef class0-0-0 fill:yellow, stroke:black
```
Parameters:
  • tree (Node) – tree to be exported

  • title (str) – title, defaults to None

  • rankdir (str) – layout direction, defaults to β€˜TB’ (top to bottom), can be β€˜BT’ (bottom to top), β€˜LR’ (left to right), β€˜RL’ (right to left)

  • line_shape (str) – line shape or curvature, defaults to β€˜basis’

  • node_colour (str) – fill colour of nodes, can be colour name or hexcode, defaults to None

  • node_border_colour (str) – border colour of nodes, can be colour name or hexcode, defaults to None

  • node_border_width (float) – width of node border, defaults to 1

  • node_shape (str) – node shape, sets the shape of every node, defaults to β€˜rounded_edge’

  • node_shape_attr (str | Callable) – If string type, it refers to Node attribute for node shape. If callable type, it takes in the node itself and returns the node shape. This sets the shape of custom nodes, and overrides default node_shape, defaults to None

  • edge_arrow (str) – edge arrow style from parent to itself, sets the arrow style of every edge, defaults to β€˜normal’

  • edge_arrow_attr (str | Callable) – If string type, it refers to Node attribute for edge arrow style. If callable type, it takes in the node itself and returns the edge arrow style. This sets the edge arrow style of custom nodes from parent to itself, and overrides default edge_arrow, defaults to None

  • edge_label (str) – Node attribute for edge label from parent to itself, defaults to None

  • node_attr (str | Callable) – If string type, it refers to Node attribute for node style. If callable type, it takes in the node itself and returns the node style. This overrides node_colour, node_border_colour, and node_border_width, defaults to None

Returns:

(str)

bigtree.tree.export.tree_to_nested_dict(tree: T, name_key: str = 'name', child_key: str = 'children', attr_dict: Dict[str, str] = {}, all_attrs: bool = False, max_depth: int = 0) Dict[str, Any]ΒΆ

Export tree to nested dictionary.

All descendants from tree will be exported, tree can be the root node or child node of tree.

Exported dictionary will have key as node attribute names, and children as a nested recursive dictionary.

>>> from bigtree import Node, tree_to_nested_dict
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> tree_to_nested_dict(root, all_attrs=True)
{'name': 'a', 'age': 90, 'children': [{'name': 'b', 'age': 65, 'children': [{'name': 'd', 'age': 40}, {'name': 'e', 'age': 35}]}, {'name': 'c', 'age': 60}]}
Parameters:
  • tree (Node) – tree to be exported

  • name_key (str) – dictionary key for node.node_name, defaults to β€˜name’

  • child_key (str) – dictionary key for list of children, optional

  • attr_dict (Dict[str, str]) – dictionary mapping node attributes to dictionary key, key: node attributes, value: corresponding dictionary key, optional

  • all_attrs (bool) – indicator whether to retrieve all Node attributes, overrides attr_dict, defaults to False

  • max_depth (int) – maximum depth to export tree, optional

Returns:

(Dict[str, Any])

bigtree.tree.export.tree_to_pillow(tree: T, width: int = 0, height: int = 0, start_pos: Tuple[int, int] = (10, 10), font_family: str = '', font_size: int = 12, font_colour: Tuple[int, int, int] | str = 'black', bg_colour: Tuple[int, int, int] | str = 'white', **kwargs: Any) Image.ImageΒΆ

Export tree to image (JPG, PNG). Image will be similar format as print_tree, accepts additional keyword arguments as input to yield_tree

>>> from bigtree import Node, tree_to_pillow
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> pillow_image = tree_to_pillow(root)

Export to image (PNG, JPG) file, etc.

>>> pillow_image.save("assets/docstr/tree_pillow.png")
>>> pillow_image.save("assets/docstr/tree_pillow.jpg")
Parameters:
  • tree (Node) – tree to be exported

  • width (int) – width of image, optional as width of image is calculated automatically

  • height (int) – height of image, optional as height of image is calculated automatically

  • start_pos (Tuple[int, int]) – start position of text, (x-offset, y-offset), defaults to (10, 10)

  • font_family (str) – file path of font family, requires .ttf file, defaults to DejaVuSans

  • font_size (int) – font size, defaults to 12

  • font_colour (Union[Tuple[int, int, int], str]) – font colour, accepts tuple of RGB values or string, defaults to black

  • bg_colour (Union[Tuple[int, int, int], str]) – background of image, accepts tuple of RGB values or string, defaults to white

Returns:

(PIL.Image.Image)

bigtree.tree.export.yield_tree(tree: T, node_name_or_path: str = '', max_depth: int = 0, style: str = 'const', custom_style: Iterable[str] = []) Iterable[Tuple[str, str, T]]ΒΆ

Generator method for customizing printing of tree, starting from tree.

  • Able to select which node to print from, resulting in a subtree, using node_name_or_path

  • Able to customize for maximum depth to print, using max_depth

  • Able to customize style, to choose from ansi, ascii, const, rounded, double, and custom style
    • Default style is const style

    • If style is set to custom, user can choose their own style for stem, branch and final stem icons

    • Stem, branch, and final stem symbol should have the same number of characters

Printing tree

>>> from bigtree import Node, yield_tree
>>> root = Node("a", age=90)
>>> b = Node("b", age=65, parent=root)
>>> c = Node("c", age=60, parent=root)
>>> d = Node("d", age=40, parent=b)
>>> e = Node("e", age=35, parent=b)
>>> for branch, stem, node in yield_tree(root):
...     print(f"{branch}{stem}{node.node_name}")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c

Printing Sub-tree

>>> for branch, stem, node in yield_tree(root, node_name_or_path="b"):
...     print(f"{branch}{stem}{node.node_name}")
b
β”œβ”€β”€ d
└── e
>>> for branch, stem, node in yield_tree(root, max_depth=2):
...     print(f"{branch}{stem}{node.node_name}")
a
β”œβ”€β”€ b
└── c

Available Styles

>>> for branch, stem, node in yield_tree(root, style="ansi"):
...     print(f"{branch}{stem}{node.node_name}")
a
|-- b
|   |-- d
|   `-- e
`-- c
>>> for branch, stem, node in yield_tree(root, style="ascii"):
...     print(f"{branch}{stem}{node.node_name}")
a
|-- b
|   |-- d
|   +-- e
+-- c
>>> for branch, stem, node in yield_tree(root, style="const"):
...     print(f"{branch}{stem}{node.node_name}")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   └── e
└── c
>>> for branch, stem, node in yield_tree(root, style="const_bold"):
...     print(f"{branch}{stem}{node.node_name}")
a
┣━━ b
┃   ┣━━ d
┃   ┗━━ e
┗━━ c
>>> for branch, stem, node in yield_tree(root, style="rounded"):
...     print(f"{branch}{stem}{node.node_name}")
a
β”œβ”€β”€ b
β”‚   β”œβ”€β”€ d
β”‚   ╰── e
╰── c
>>> for branch, stem, node in yield_tree(root, style="double"):
...     print(f"{branch}{stem}{node.node_name}")
a
╠══ b
β•‘   ╠══ d
β•‘   β•šβ•β• e
β•šβ•β• c

Printing Attributes

>>> for branch, stem, node in yield_tree(root, style="const"):
...     print(f"{branch}{stem}{node.node_name} [age={node.age}]")
a [age=90]
β”œβ”€β”€ b [age=65]
β”‚   β”œβ”€β”€ d [age=40]
β”‚   └── e [age=35]
└── c [age=60]
Parameters:
  • tree (Node) – tree to print

  • node_name_or_path (str) – node to print from, becomes the root node of printing, optional

  • max_depth (int) – maximum depth of tree to print, based on depth attribute, optional

  • style (str) – style of print, defaults to abstract style

  • custom_style (Iterable[str]) – style of stem, branch and final stem, used when style is set to β€˜custom’