pyTooling.Tree
A powerful tree data structure for Python.
Exceptions
TreeException
: Base exception of all exceptions raised bypyTooling.Tree
.InternalError
: The exception is raised when a data structure corruption is detected.NoSiblingsError
: The exception is raised when a node has no parent and thus has no siblings.AlreadyInTreeError
: The exception is raised when the current node and the other node are already in the same tree.NotInSameTreeError
: The exception is raised when the current node and the other node are not in the same tree.
Classes
Node
: A tree data structure can be constructed ofNode
instances.
Exceptions
- exception pyTooling.Tree.TreeException[source]
Base exception of all exceptions raised by
pyTooling.Tree
.Inheritance
- exception pyTooling.Tree.InternalError[source]
The exception is raised when a data structure corruption is detected.
Danger
This exception should never be raised.
If so, please create an issue at GitHub so the data structure corruption can be investigated and fixed.
⇒ Bug Tracker at GitHubInheritance
- exception pyTooling.Tree.NoSiblingsError[source]
The exception is raised when a node has no parent and thus has no siblings.
Hint
A node with no parent is the root node of the tree.
Inheritance
- exception pyTooling.Tree.AlreadyInTreeError[source]
The exception is raised when the current node and the other node are already in the same tree.
Hint
A tree a an acyclic graph without cross-edges. Thus backward edges and cross edges are permitted.
Inheritance
- exception pyTooling.Tree.NotInSameTreeError[source]
The exception is raised when the current node and the other node are not in the same tree.
Inheritance
Classes
- class pyTooling.Tree.Node(nodeID=None, value=None, parent=None, children=None)[source]
A tree data structure can be constructed of
Node
instances.Therefore, nodes can be connected to parent nodes or a parent node can add child nodes. This allows to construct a tree top-down or bottom-up.
Hint
The top-down construction should be preferred, because it’s slightly faster.
Each tree uses the root node (a.k.a. tree-representative) to store some per-tree data structures. E.g. a list of all IDs in a tree. For easy and quick access to such data structures, each sibling node contains a reference to the root node (
_root
). In case of adding a tree to an existing tree, such data structures get merged and all added nodes get assigned with new root references. Use the read-only propertyRoot
to access the root reference.The reference to the parent node (
_parent
) can be access via propertyParent
. If the property’s setter is used, a node and all its siblings are added to another tree or to a new position in the same tree.The references to all node’s children is stored in a list (
_children
). Children, siblings, ancestors, can be accessed via various generators:GetAncestors()
→ iterate all ancestors bottom-up.GetChildren()
→ iterate all direct children.GetDescendants()
→ iterate all descendants.IterateLevelOrder()
→ IterateLevelOrder.IteratePreOrder()
→ iterate siblings in pre-order.IteratePostOrder()
→ iterate siblings in post-order.
Each node can have a unique ID or no ID at all (
nodeID=None
). The root node is used to store all IDs in a dictionary (_nodesWithID
). In case no ID is given, all such ID-less nodes are collected in a single bin and store as a list of nodes. An ID can be modified after the Node was created. Use the read-only propertyID
to access the ID.Each node can have a value (
_value
), which can be given at node creation time, or it can be assigned and/or modified later. Use the propertyValue
to get or set the value.Moreover, each node can store various key-value-pairs (
_dict
). Use the dictionary syntax to get and set key-value-pairs.Inheritance
- Parameters:
- __init__(nodeID=None, value=None, parent=None, children=None)[source]
Todo
TREE::Node::init Needs documentation.
-
_dict:
Dict
[TypeVar
(DictKeyType
),TypeVar
(DictValueType
)] Dictionary to store key-value-pairs attached to the node.
-
_nodesWithoutID:
Optional
[List
[Node
]] List of all nodes without an ID in the tree.
None
if it’s not the root node.
-
_nodesWithID:
Optional
[Dict
[TypeVar
(IDType
, bound=Hashable
),Node
]] Dictionary of all IDs in the tree.
None
if it’s not the root node.
- property ID: IDType | None
Read-only property to access the unique ID of a node (
_id
).If no ID was given at node construction time, ID return None.
- Returns:
Unique ID of a node, if ID was given at node creation time, else None.
- property Value: ValueType | None
Property to get and set the value (
_value
) of a node.- Returns:
The value of a node.
- __setitem__(key, value)[source]
Create or update a node’s attached attributes (key-value-pairs) by key.
If a key doesn’t exist yet, a new key-value-pair is created.
- __delitem__(key)[source]
Todo
TREE::Node::__delitem__ Needs documentation.
- Return type:
- Parameters:
key (DictKeyType)
- __contains__(key)[source]
Todo
TREE::Node::__contains__ Needs documentation.
- Return type:
- Parameters:
key (DictKeyType)
- property Root: Node
Read-only property to access the tree’s root node (
_root
).- Returns:
The root node (representative node) of a tree.
- property Parent: Node | None
Property to get and set the parent (
_parent
) of a node.Note
As the current node might be a tree itself, appending this node to a tree can lead to a merge of trees and especially to a merge of IDs. As IDs are unique, it might raise an
Exception
.- Returns:
The parent of a node.
- Raises:
AlreadyInTreeError – Parent is already a child node in this tree.
- property Siblings: Tuple[Node, ...]
A read-only property to return a tuple of all siblings from the current node.
If the current node is the only child, the tuple is empty.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Returns:
A tuple of all siblings of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- property LeftSiblings: Tuple[Node, ...]
A read-only property to return a tuple of all siblings left from the current node.
If the current node is the only child, the tuple is empty.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Returns:
A tuple of all siblings left of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- property RightSiblings: Tuple[Node, ...]
A read-only property to return a tuple of all siblings right from the current node.
If the current node is the only child, the tuple is empty.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Returns:
A tuple of all siblings right of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- _GetPathAsLinkedList()[source]
Compute the path from current node to root node by using a linked list (
deque
).
- property Path: Tuple[Node]
Read-only property to return the path from root node to the node as a tuple of nodes.
- Returns:
A tuple of nodes describing the path from root node to the node.
- property Level: int
Read-only property to return a node’s level in the tree.
The level is the distance to the root node.
- Returns:
The node’s level.
- property Size: int
Read-only property to return the size of the tree.
- Returns:
Count of all nodes in the tree structure.
- property IsRoot: bool
Returns true, if the node is the root node (representative node of the tree).
- Returns:
True
, if node is the root node.
- property IsLeaf: bool
Returns true, if the node is a leaf node (has no children).
- Returns:
True
, if node has no children.
- property HasChildren: bool
Returns true, if the node has child nodes.
- Returns:
True
, if node has children.
- AddChild(child)[source]
Add a child node to the current node of the tree.
If
child
is a subtree, both trees get merged. So all nodes inchild
get a new_root
assigned and all IDs are merged into the node’s root’s ID lists (_nodesWithID
).- Parameters:
child (
Node
) – The child node to be added to the tree.- Raises:
AlreadyInTreeError – If parameter
child
is already a node in the tree.
See also
Parent
→ Set the parent of a node.
AddChildren()
→ Add multiple children at once.
- AddChildren(children)[source]
Add multiple children nodes to the current node of the tree.
- Parameters:
children (
Iterable
[Node
]) – The list of children nodes to be added to the tree.- Raises:
TypeError – If parameter
children
contains an item, which is not aNode
.AlreadyInTreeError – If parameter
children
contains an item, which is already a node in the tree.
See also
Parent
→ Set the parent of a node.
AddChild()
→ Add a child node to the tree.
- GetChildren()[source]
A generator to iterate all direct children of the current node.
See also
GetDescendants()
→ Iterate all descendants.
IterateLevelOrder()
→ Iterate items level-by-level, which includes the node itself as a first returned node.
IteratePreOrder()
→ Iterate items in pre-order, which includes the node itself as a first returned node.
IteratePostOrder()
→ Iterate items in post-order, which includes the node itself as a last returned node.
- class property HasClassAttributes: bool
Check if class has Attributes.
- Returns:
True
, if the class has Attributes.
- class property HasMethodAttributes: bool
Check if class has any method with Attributes.
- Returns:
True
, if the class has any method with Attributes.
- __class_getitem__()
Parameterizes a generic class.
At least, parameterizing a generic class is the main thing this method does. For example, for some generic class Foo, this is called when we do Foo[int] - there, with cls=Foo and params=int.
However, note that this method is also called when defining generic classes in the first place with class Foo[T]: ….
- __init_subclass__()
Function to initialize subclasses.
- GetSiblings()[source]
A generator to iterate all siblings.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Return type:
- Returns:
A generator to iterate all siblings of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- GetLeftSiblings()[source]
A generator to iterate all siblings left from the current node.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Return type:
- Returns:
A generator to iterate all siblings left of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- GetRightSiblings()[source]
A generator to iterate all siblings right from the current node.
Siblings are child nodes of the current node’s parent node, without the current node itself.
- Return type:
- Returns:
A generator to iterate all siblings right of the current node.
- Raises:
NoSiblingsError – If the current node has no parent node and thus no siblings.
- GetDescendants()[source]
A generator to iterate all descendants of the current node. In contrast to IteratePreOrder and IteratePostOrder it doesn’t include the node itself.
See also
GetChildren()
→ Iterate all children, but no grand-children.
IterateLevelOrder()
→ Iterate items level-by-level, which includes the node itself as a first returned node.
IteratePreOrder()
→ Iterate items in pre-order, which includes the node itself as a first returned node.
IteratePostOrder()
→ Iterate items in post-order, which includes the node itself as a last returned node.
- GetRelatives()[source]
A generator to iterate all relatives (all siblings and all their descendants) of the current node.
- Returns:
A generator to iterate all relatives.
- GetLeftRelatives()[source]
A generator to iterate all left relatives (left siblings and all their descendants) of the current node.
- Returns:
A generator to iterate all left relatives.
- GetRightRelatives()[source]
A generator to iterate all right relatives (right siblings and all their descendants) of the current node.
- Returns:
A generator to iterate all right relatives.
- IterateLeafs()[source]
A generator to iterate all leaf-nodes in a subtree, which subtree root is the current node.
- IterateLevelOrder()[source]
A generator to iterate all siblings of the current node level-by-level top-down. In contrast to GetDescendants, this includes also the node itself as the first returned node.
- Return type:
- Returns:
A generator to iterate all siblings level-by-level.
See also
GetChildren()
→ Iterate all children, but no grand-children.
GetDescendants()
→ Iterate all descendants.
IteratePreOrder()
→ Iterate items in pre-order, which includes the node itself as a first returned node.
IteratePostOrder()
→ Iterate items in post-order, which includes the node itself as a last returned node.
- IteratePreOrder()[source]
A generator to iterate all siblings of the current node in pre-order. In contrast to GetDescendants, this includes also the node itself as the first returned node.
See also
GetChildren()
→ Iterate all children, but no grand-children.
GetDescendants()
→ Iterate all descendants.
IterateLevelOrder()
→ Iterate items level-by-level, which includes the node itself as a first returned node.
IteratePostOrder()
→ Iterate items in post-order, which includes the node itself as a last returned node.
- IteratePostOrder()[source]
A generator to iterate all siblings of the current node in post-order. In contrast to GetDescendants, this includes also the node itself as the last returned node.
- Return type:
- Returns:
A generator to iterate all siblings in post-order.
See also
GetChildren()
→ Iterate all children, but no grand-children.
GetDescendants()
→ Iterate all descendants.
IterateLevelOrder()
→ Iterate items level-by-level, which includes the node itself as a first returned node.
IteratePreOrder()
→ Iterate items in pre-order, which includes the node itself as a first returned node.
- GetNodeByID(nodeID)[source]
Lookup a node by its unique ID.
- Parameters:
nodeID (
TypeVar
(IDType
, bound=Hashable
)) – ID of a node to lookup in the tree.- Return type:
- Returns:
Node for the given ID.
- Raises:
ValueError – If parameter
nodeID
is None.KeyError – If parameter
nodeID
is not found in the tree.
- __len__()[source]
Returns the number of children, but not including grand-children.
- Return type:
- Returns:
Number of child nodes.
- __repr__()[source]
Returns a detailed string representation of the node.
- Return type:
- Returns:
The detailed string representation of the node.
- __str__()[source]
Return a string representation of the node.
Order of resolution:
If
_value
is not None, return the string representation of_value
.If
_id
is not None, return the string representation of_id
.Else, return
__repr__()
.
- Return type:
- Returns:
The resolved string representation of the node.
- Render(prefix='', lineend='\\n', nodeMarker='o-- ', bypassMarker='| ')[source]
Render the tree as ASCII art.
- Parameters:
prefix (
str
) – A string printed in front of every line, e.g. for indentation. Default:""
.lineend (
str
) – A string printed at the end of every line. Default:"\n"
.nodeMarker (
str
) – A string printed before every tree node. Default:"o-- "
.bypassMarker (
str
) – A string printed when there are further nodes in the parent level. Default:"| "
.
- Return type:
- Returns:
A rendered tree as multiline string.