GHPython Universal flatten Tree (structure)

Coding in GHPython it would be usefull to have an unniversal flatten to handle mixed data types, and sort it all out from python to grasshopper.

def flatten_all(obj):
from ghpythonlib.treehelpers import flatten
from Grasshopper import DataTree
from System.Collections import IEnumerable

# If the object is a DataTree, extract its branches and concatenate all items
if isinstance(obj, DataTree):
    return [item for branch in obj.Branches for item in branch]

# If the object is a .NET collection (e.g. direct output from gh.Flatten)
elif isinstance(obj, IEnumerable) and not isinstance(obj, (str, bytes)):
    try:
        # Use GH helper to flatten lists of lists
        return flatten(obj)
    except:
        pass

# If the object is a Python list or tuple (nested structure)
elif isinstance(obj, (list, tuple)):
    flat = []
    for item in obj:
        # Recurse into nested structures
        flat.extend(flatten_all(item))
    return flat

# For any other object, return it as a single-item list
else:
    return [obj]
1 Like