`Block.tree()` doesn't support depth limit
- Dominant language
- Python
- Stars
- 13
- Forks
- 9
- PR merge metrics
- No merged PRs in 30d
Description
`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`:
```python
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:
```python
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:
```python
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()`:
```python
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`
Contributor guide
Research direction
Start in dag/block.py at Block.tree() and the _walk_tree() helper, then inspect how the current depth-first paths are produced. Verify the existing unlimited behavior and the requested depth cases from the issue: depth 0 yields nothing, depth 1 yields top-level paths, and the default remains unlimited.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- distributed-systems
- Issue type
- Feature
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 85/100