Skip to content

Commit eff2b2e

Browse files
committed
add node_repr option to tree
1 parent 58571a0 commit eff2b2e

1 file changed

Lines changed: 15 additions & 6 deletions

File tree

  • src/compas/datastructures/tree

src/compas/datastructures/tree/tree.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ def get_node_by_name(self, name):
412412
413413
"""
414414
for node in self.nodes:
415-
if node.name == name:
415+
if str(node.name) == str(name):
416416
return node
417417

418418
def get_nodes_by_name(self, name):
@@ -436,7 +436,7 @@ def get_nodes_by_name(self, name):
436436
nodes.append(node)
437437
return nodes
438438

439-
def get_hierarchy_string(self, max_depth=None):
439+
def get_hierarchy_string(self, max_depth=None, node_repr=None):
440440
"""
441441
Return string representation for the spatial hierarchy of the tree.
442442
@@ -445,6 +445,10 @@ def get_hierarchy_string(self, max_depth=None):
445445
max_depth : int, optional
446446
The maximum depth of the hierarchy to print.
447447
Default is ``None``, in which case the entire hierarchy is printed.
448+
node_repr : callable, optional
449+
A callable to represent the node string.
450+
Default is ``None``, in which case the node.__repr__() is used.
451+
448452
449453
Returns
450454
-------
@@ -455,17 +459,22 @@ def get_hierarchy_string(self, max_depth=None):
455459

456460
hierarchy = []
457461

458-
def traverse(node, hierarchy, prefix="", last=True, depth=0):
462+
def traverse(node, hierarchy, prefix="", last=True, depth=0, node_repr=None):
459463
if max_depth is not None and depth > max_depth:
460464
return
461465

466+
if node_repr is None:
467+
node_string = node.__repr__()
468+
else:
469+
node_string = node_repr(node)
470+
462471
connector = "└── " if last else "├── "
463-
hierarchy.append("{}{}{}".format(prefix, connector, node))
472+
hierarchy.append("{}{}{}".format(prefix, connector, node_string))
464473
prefix += " " if last else "│ "
465474
for i, child in enumerate(node.children):
466-
traverse(child, hierarchy, prefix, i == len(node.children) - 1, depth + 1)
475+
traverse(child, hierarchy, prefix, i == len(node.children) - 1, depth + 1, node_repr)
467476

468-
traverse(self.root, hierarchy)
477+
traverse(self.root, hierarchy, node_repr=node_repr)
469478

470479
return "\n".join(hierarchy)
471480

0 commit comments

Comments
 (0)