Created
March 26, 2026 17:05
-
-
Save flying-sheep/b4274c148a08b7f037c732bec4a163a5 to your computer and use it in GitHub Desktop.
Controlling descent in an iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from collections.abc import Generator, Mapping, Sequence | |
| @dataclass | |
| class Hier[T]: | |
| things: Mapping[T, Sequence[T]] | |
| descend = True | |
| def __iter__(self) -> Generator[T]: | |
| for cat, children in self.things.items(): | |
| yield cat | |
| if self.descend: | |
| yield from children | |
| self.descend = True | |
| things = {"a": ("a.1", "a.2"), "b": ("b.1", "b.2")} | |
| print("all:") | |
| for thing in Hier(things): | |
| print(thing) | |
| print() | |
| print("no a.*:") | |
| for thing in (hier := Hier(things)): | |
| if thing == "a": | |
| hier.descend = False | |
| print(thing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment