Skip to content

Block.tree() doesn't support depth limit #28

Description

@sumanjeet0012

Block.tree() always traverses the entire tree. Go's Tree(path, depth) supports a depth parameter to limit traversal. This is useful for large DAGs where you only want to see the top-level structure.

Problem

In dag/block.py:

def tree(self) -> Iterator[str]:
    """Yield every path segment in this block's value (depth-first)."""
    yield from _walk_tree(self._value, "")

There's no way to limit the depth:

block = Block.encode(
    value={"a": {"b": {"c": "deep"}}},
    codec=dag_cbor.codec,
)

list(block.tree())  # → ["a", "a/b", "a/b/c"]
# No way to get just: ["a"]

Proposed Solution

Add an optional depth parameter:

def tree(self, depth: int = -1) -> Iterator[str]:
    """Yield every path segment in this block's value (depth-first).

    Parameters
    ----------
    depth:
        Maximum depth to traverse. -1 means unlimited (default).
        0 yields nothing. 1 yields only top-level keys.
    """
    if depth == 0:
        return
    yield from _walk_tree(self._value, "", max_depth=depth, current_depth=0)

Update _walk_tree():

def _walk_tree(node, prefix, max_depth=-1, current_depth=0):
    if max_depth >= 0 and current_depth >= max_depth:
        return
    if isinstance(node, dict):
        for k, v in node.items():
            child = f"{prefix}/{k}" if prefix else k
            yield child
            yield from _walk_tree(v, child, max_depth, current_depth + 1)
    elif isinstance(node, list):
        for i, v in enumerate(node):
            child = f"{prefix}/{i}" if prefix else str(i)
            yield child
            yield from _walk_tree(v, child, max_depth, current_depth + 1)

Related

  • Go implementation: go-ipld-prime Node.Tree() method
  • File: dag/block.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions