Best Methods to Navigate DataTrees in Python?

Hi,

This is a general question on working with Grasshopper DataTrees using Python.

Assuming that I have a DataTree with multiple levels in the path (is ‘levels’ the right word?), is there a good built-in way to iterate over just one level at a time?

For instance, if I have a DataTree which is shaped like:

{0;0}=[0, 1].
{0;1}=[2, 3],
{0;2}=[4, 5],
{1;0}=[6, 7],
{1;1}=[8, 9],
{1;2}=[10, 11], 
...

Is there a nice way to easily iterate over each level at a time? So, what I mean is: walk through all the {0;…}s first, then walk through all the {1;…}s, etc…?


The best I could come up with was something like this:

from Grasshopper import DataTree
from Grasshopper.Kernel.Data import GH_Path
from typing import Any, Tuple, Generator

def tree_branches(_tree: DataTree, _branch_level: int) -> Generator[tuple[Any, Any], Any, None]:
    for p in _tree.Paths:
        if p[0] == _branch_level:
            yield (p, _tree.Branch(p))

levels = {_[0] for _ in _tree.Paths}
for level in levels:
    print(level, "- "* 25)
    
    for p, branch in tree_branches(_tree, level):
        print(p, list(branch))

The above does work the way I want, and gives me the output:

0 - - - - - - - - - - - - - - - - - - - - - - - - - 
{0;0} [0, 1]
{0;1} [2, 3]
{0;2} [4, 5]
1 - - - - - - - - - - - - - - - - - - - - - - - - - 
{1;0} [6, 7]
{1;1} [8, 9]
{1;2} [10, 11]

But it doesn’t seem very elegant, and made me think there must be a better built-in way to accomplish this behavior since it seems like a fairly common need? Does anyone know of any better methods to do this?

Any thoughts are much appreciated. Thanks!
@ed.p.may

Try importing ghpythonlib.treehelpers.