typing improvements

This commit is contained in:
Will McGugan
2022-10-13 21:01:04 +01:00
parent 7eb5119fe0
commit de4ca1509e

View File

@@ -670,7 +670,7 @@ class DOMNode(MessagePump):
""" """
def walk_depth_first() -> Iterable[DOMNode]: def walk_depth_first() -> Iterable[DOMNode]:
"""Walk the tree breadth first (parent's first).""" """Walk the tree depth first (parents first)."""
stack: list[Iterator[DOMNode]] = [iter(self.children)] stack: list[Iterator[DOMNode]] = [iter(self.children)]
pop = stack.pop pop = stack.pop
push = stack.append push = stack.append
@@ -678,7 +678,6 @@ class DOMNode(MessagePump):
if with_self and isinstance(self, check_type): if with_self and isinstance(self, check_type):
yield self yield self
while stack: while stack:
node = next(stack[-1], None) node = next(stack[-1], None)
if node is None: if node is None:
@@ -690,17 +689,18 @@ class DOMNode(MessagePump):
push(iter(node.children)) push(iter(node.children))
def walk_breadth_first() -> Iterable[DOMNode]: def walk_breadth_first() -> Iterable[DOMNode]:
"""Walk the tree depth first (children first).""" """Walk the tree breadth first (children first)."""
queue: deque[DOMNode] = deque() queue: deque[DOMNode] = deque()
popleft = queue.popleft popleft = queue.popleft
extend = queue.extend extend = queue.extend
check_type = filter_type or DOMNode
if with_self: if with_self and isinstance(self, check_type):
yield self yield self
queue.extend(self.children) extend(self.children)
while queue: while queue:
node = popleft() node = popleft()
if isinstance(node, check_type):
yield node yield node
extend(node.children) extend(node.children)
@@ -708,10 +708,10 @@ class DOMNode(MessagePump):
walk_depth_first() if method == "depth" else walk_breadth_first() walk_depth_first() if method == "depth" else walk_breadth_first()
) )
nodes = list(node_generator)
if reverse: if reverse:
yield from reversed(list(node_generator)) nodes.reverse()
else: yield from nodes
yield from node_generator
def get_child(self, id: str) -> DOMNode: def get_child(self, id: str) -> DOMNode:
"""Return the first child (immediate descendent) of this node with the given ID. """Return the first child (immediate descendent) of this node with the given ID.