Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

faster walk #5067

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions src/textual/walk.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,29 +50,37 @@ def walk_depth_first(

Args:
root: The root note (starting point).
filter_type: Optional DOMNode subclass to filter by, or ``None`` for no filter.
filter_type: Optional DOMNode subclass to filter by, or `None` for no filter.
with_root: Include the root in the walk.

Returns:
An iterable of DOMNodes, or the type specified in ``filter_type``.
An iterable of DOMNodes, or the type specified in `filter_type`.
"""
from textual.dom import DOMNode

stack: list[Iterator[DOMNode]] = [iter(root.children)]
pop = stack.pop
push = stack.append
check_type = filter_type or DOMNode

if with_root and isinstance(root, check_type):
yield root
while stack:
if (node := next(stack[-1], None)) is None:
pop()
else:
if isinstance(node, check_type):
if filter_type is None:
if with_root:
yield root
while stack:
if (node := next(stack[-1], None)) is None:
pop()
else:
yield node
if children := node._nodes:
push(iter(children))
if children := node._nodes:
push(iter(children))
else:
if with_root and isinstance(root, filter_type):
yield root
while stack:
if (node := next(stack[-1], None)) is None:
pop()
else:
if isinstance(node, filter_type):
willmcgugan marked this conversation as resolved.
Show resolved Hide resolved
yield node
if children := node._nodes:
push(iter(children))


if TYPE_CHECKING:
Expand Down Expand Up @@ -108,11 +116,11 @@ def walk_breadth_first(

Args:
root: The root note (starting point).
filter_type: Optional DOMNode subclass to filter by, or ``None`` for no filter.
filter_type: Optional DOMNode subclass to filter by, or `None` for no filter.
with_root: Include the root in the walk.

Returns:
An iterable of DOMNodes, or the type specified in ``filter_type``.
An iterable of DOMNodes, or the type specified in `filter_type`.
"""
from textual.dom import DOMNode

Expand Down
Loading