Skip to content

Commit c5f8726

Browse files
authored
Merge pull request #5067 from Textualize/optimize-walk
faster walk
2 parents d472cb5 + 8615d6d commit c5f8726

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

src/textual/walk.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,29 +50,37 @@ def walk_depth_first(
5050
5151
Args:
5252
root: The root note (starting point).
53-
filter_type: Optional DOMNode subclass to filter by, or ``None`` for no filter.
53+
filter_type: Optional DOMNode subclass to filter by, or `None` for no filter.
5454
with_root: Include the root in the walk.
5555
5656
Returns:
57-
An iterable of DOMNodes, or the type specified in ``filter_type``.
57+
An iterable of DOMNodes, or the type specified in `filter_type`.
5858
"""
59-
from textual.dom import DOMNode
60-
6159
stack: list[Iterator[DOMNode]] = [iter(root.children)]
6260
pop = stack.pop
6361
push = stack.append
64-
check_type = filter_type or DOMNode
6562

66-
if with_root and isinstance(root, check_type):
67-
yield root
68-
while stack:
69-
if (node := next(stack[-1], None)) is None:
70-
pop()
71-
else:
72-
if isinstance(node, check_type):
63+
if filter_type is None:
64+
if with_root:
65+
yield root
66+
while stack:
67+
if (node := next(stack[-1], None)) is None:
68+
pop()
69+
else:
7370
yield node
74-
if children := node._nodes:
75-
push(iter(children))
71+
if children := node._nodes:
72+
push(iter(children))
73+
else:
74+
if with_root and isinstance(root, filter_type):
75+
yield root
76+
while stack:
77+
if (node := next(stack[-1], None)) is None:
78+
pop()
79+
else:
80+
if isinstance(node, filter_type):
81+
yield node
82+
if children := node._nodes:
83+
push(iter(children))
7684

7785

7886
if TYPE_CHECKING:
@@ -108,11 +116,11 @@ def walk_breadth_first(
108116
109117
Args:
110118
root: The root note (starting point).
111-
filter_type: Optional DOMNode subclass to filter by, or ``None`` for no filter.
119+
filter_type: Optional DOMNode subclass to filter by, or `None` for no filter.
112120
with_root: Include the root in the walk.
113121
114122
Returns:
115-
An iterable of DOMNodes, or the type specified in ``filter_type``.
123+
An iterable of DOMNodes, or the type specified in `filter_type`.
116124
"""
117125
from textual.dom import DOMNode
118126

0 commit comments

Comments
 (0)