From ea1a5a31b239ffc1c877239f9296fdc5f7151864 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Fri, 27 Sep 2024 15:29:44 +0100 Subject: [PATCH 1/2] faster walk --- src/textual/walk.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/textual/walk.py b/src/textual/walk.py index 0f6790c882..3f158abc24 100644 --- a/src/textual/walk.py +++ b/src/textual/walk.py @@ -56,23 +56,31 @@ def walk_depth_first( Returns: 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): + yield node + if children := node._nodes: + push(iter(children)) if TYPE_CHECKING: From 8615d6d876931083302141fe76a975d53d44dffb Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Sun, 29 Sep 2024 19:19:25 +0100 Subject: [PATCH 2/2] docstring syntax --- src/textual/walk.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/textual/walk.py b/src/textual/walk.py index 3f158abc24..dcda856e49 100644 --- a/src/textual/walk.py +++ b/src/textual/walk.py @@ -50,11 +50,11 @@ 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`. """ stack: list[Iterator[DOMNode]] = [iter(root.children)] pop = stack.pop @@ -116,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