Encodes Python stdlib idioms for iteration (generators, itertools, async iteration) and tree composition (dataclass-based leaf/composite structures, recursive traversal, exhaustive match dispatch).
Ships in pystack-python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Two common-but-distinct Python data idioms that don't fit the typing-idioms or value-objects skills, bundled here because each on its own is too thin to be a standalone skill. Use the section that matches your task.
itertools, lazy pipelines, async iterationfor ... in ... loopA AND (B OR C))The GoF Iterator pattern exists for languages without first-class iteration. Python has had the iterator protocol (__iter__ / __next__), generators, and itertools since 2.2. There is almost never a reason to write a class with __next__ by hand.
# Good — three lines, all the iterator machinery is implicit
def line_numbers(lines: Iterable[str]) -> Iterator[tuple[int, str]]:
for i, line in enumerate(lines, start=1):
yield i, line
# Bad — implementing the protocol when generators would do it
class LineNumberIterator:
def __init__(self, lines: Iterable[str]) -> None:
self._lines = iter(lines)
self._i = 0
def __iter__(self) -> "LineNumberIterator":
return self
def __next__(self) -> tuple[int, str]:
self._i += 1
return self._i, next(self._lines)
Generators are the iterator protocol with the right defaults. yield makes a function pause and resume; the generator object handles __iter__, __next__, StopIteration, and send/throw for free.
itertools for stream compositionfrom itertools import chain, groupby, islice, takewhile, pairwise
combined = chain(orders_today, orders_yesterday) # concatenate lazily
first_100 = islice(big_iter, 100) # first 100 only
for status, group in groupby(orders, key=lambda o: o.status):
print(status, list(group)) # consecutive runs by key
Memorize: chain, islice, takewhile, dropwhile, groupby, accumulate, pairwise, tee. Composing them is usually faster and clearer than nested for loops with ifs.
totals = (order.total for order in orders if order.status == "placed")
big = (t for t in totals if t > Decimal("1000"))
result = sum(big)
Each generator expression is a lazy stream. They compose by being passed to each other. Reach for list(...) only when you genuinely need a list (multiple passes, indexing, length).
AsyncIterator[T] and async forfrom collections.abc import AsyncIterator
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
async def stream_orders(session: AsyncSession) -> AsyncIterator[Order]:
stmt = select(Order)
result = await session.stream_scalars(stmt)
async for order in result:
yield order
async for order in stream_orders(session):
print(order.id)
async def ... yield ... makes an async generator. Use this for any production-sized result set — stream_scalars doesn't buffer everything in memory.
Iterable[T] for inputs, Iterator[T] for outputsfrom collections.abc import Iterable, Iterator
def line_numbers(lines: Iterable[str]) -> Iterator[tuple[int, str]]:
for i, line in enumerate(lines, start=1):
yield i, line
Iterable[T] is widest (everything that supports iter()). Use it for parameters — be liberal in what you accept. Iterator[T] is what generators return — use it for return types. Avoid list[T] parameters when you only need to iterate; it forces callers to materialize.
For async: AsyncIterable[T] for input, AsyncIterator[T] for output.
yield fromdef all_lines(files: list[Path]) -> Iterator[str]:
for path in files:
with path.open() as f:
yield from f
yield from flattens nested iteration. Equivalent to for line in f: yield line but shorter and more efficient.
next() with a defaultfirst_active = next((u for u in users if u.is_active), None)
Clean for "find one or fall back" — no try/except StopIteration.
__iter__ on your own class only when the class IS a collectionfrom collections.abc import Iterator
class Inventory:
def __init__(self) -> None:
self._items: dict[ProductId, int] = {}
def __iter__(self) -> Iterator[tuple[ProductId, int]]:
return iter(self._items.items())
def __len__(self) -> int:
return len(self._items)
Fine to implement __iter__ when iteration over the object's contents makes natural sense (for product, qty in inventory:). Don't write a class whose only purpose is __next__ — use a generator function.
Sequence[T] or list[T].When data is recursive (filesystem, AST, query tree, UI hierarchy), the Pythonic shape is dataclass leaves and composites, tied together by a type that names every node kind. Same shape as the GoF Composite pattern, less ceremony.
type FileSystemNode = File | Directory
A PEP 695 alias is lazy, so it can be declared before File and Directory exist and used inside their annotations. Every function that takes a node takes FileSystemNode. Because the union lists every kind by name, the type checker knows the full set — which is what makes match over it exhaustive (rule 8). No base class, no inheritance.
When the set of node kinds is open — plugins or third-party code add their own — use a Protocol for the shared methods instead:
from typing import Protocol
class FileSystemNode(Protocol):
name: str
def size(self) -> int: ...
That trade gives up exhaustive match: any class with those methods is a node, so no checker can prove a match over it covers every case. With an open set, dispatch through methods on the nodes (rule 3), not through functions that switch on type.
from dataclasses import dataclass
@dataclass(slots=True, kw_only=True)
class File:
name: str
bytes: int
def size(self) -> int:
return self.bytes
def display(self, indent: int = 0) -> None:
print(" " * indent + f"📄 {self.name} ({self.bytes}B)")
No special "leaf" decoration or base class. Just a class with the same methods as its sibling node kinds.
@dataclass(slots=True, kw_only=True)
class Directory:
name: str
children: list[FileSystemNode]
def size(self) -> int:
return sum(child.size() for child in self.children)
def display(self, indent: int = 0) -> None:
print(" " * indent + f"📁 {self.name}/")
for child in self.children:
child.display(indent + 2)
The composite's methods recursively delegate to children. Callers don't know or care whether they're holding a File or a Directory — they just call node.size().
from collections.abc import Iterator
def walk(node: FileSystemNode) -> Iterator[FileSystemNode]:
yield node
if isinstance(node, Directory):
for child in node.children:
yield from walk(child)
Don't put traversal on every leaf as a no-op. Walk is a free function (or lives with the composite). Use generators — lazy, composable, cheap.
@dataclass(slots=True, kw_only=True)
class Directory:
...
def find_by_name(self, name: str) -> FileSystemNode | None:
for node in walk(self):
if node.name == name:
return node
return None
find_by_name only makes sense on a directory (a tree root). Don't add it to every node kind; leaves don't need it.
@dataclass(slots=True, kw_only=True)
class Leaf[T]:
value: T
@dataclass(slots=True, kw_only=True)
class Node[T]:
children: list["Leaf[T] | Node[T]"]
def values(self) -> Iterator[T]:
for child in self.children:
if isinstance(child, Leaf):
yield child.value
else:
yield from child.values()
Generic composites are useful for expression trees over typed values (Tree[int], Tree[Expr]).
field(default_factory=list), not [], for mutable defaults@dataclass
class Leaf:
tags: list[str] = field(default_factory=list) # not = []
Dataclasses catch the mutable-default case, but the lesson generalizes.
match over the unionfrom typing import assert_never
def to_html(node: FileSystemNode) -> str:
match node:
case File(name=name):
return f"<a>{name}</a>"
case Directory(name=name, children=children):
inner = "".join(to_html(c) for c in children)
return f"<ul><li>{name}{inner}</li></ul>"
case _:
assert_never(node)
match over a closed union is the modern visitor: clean syntax, no accept(visitor) ceremony, and exhaustiveness checking. Add Symlink to FileSystemNode and the type checker flags the assert_never(node) line in every visitor that doesn't handle it yet. That check only exists because the union is closed (rule 1) — over a Protocol-typed node, assert_never can never type-check.
Protocol — union when you own every node kind (exhaustive match); Protocol when the set is open (behavior as methods on the nodes, no type-switching functions).ABC — only if node kinds must share method implementations (rare for trees).walk with cycle protection. set[id(node)] is fine for unhashable nodes.__iter__ returning self and __next__ doing the work, when a generator function would have produced the same iterator in three lines.[t for t in totals if t > 1000] builds a full list before consuming. Use (t for t in totals if t > 1000) if you only need to iterate / sum / pass through.Component class with add_child / remove_child on every node — the GoF approach. Leaves don't need those methods; making the interface include them sacrifices type safety for false symmetry.isinstance checks scattered through the codebase — dispatch with an exhaustive match over the closed union, or put the behavior on the nodes as methods.python-typing-idioms — Protocol, PEP 695 generics, Iterable[T], AsyncIterator[T]python-aggregate-and-repo — AsyncIterator[T] return types on repo methodspython-antipatterns-cheatsheet — GoF Iterator / Visitor / Abstract Factory redirectsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/pystack-python:python-stdlib-idiomsfrom pystack-python
npx claudepluginhub denyszhak/pystack-skills --plugin pystack-python4 skills in this plugin
/python-antipatterns-cheatsheetUse when considering a Java/GoF-shaped pattern that agents commonly generate in
Python: Singleton, Abstract Factory, or Factory Method. Use when reviewing code
defining `class *Singleton`, `class Abstract*Factory`, `*Factory.create(...)`, or
when the user asks "is X a good idea in Python?" Encodes: which imported
patterns usually add ceremony in Python, what to use instead, and which positive
skill has the detail.
Do NOT use for: deep dives — this is the quick lookup. Each entry points to
the positive skill with the full alternative.
/python-typing-idiomsUse when writing or modifying typed Python code (any project — libraries, services,
scripts). Triggers on `.py` files with type annotations; on imports from `typing`,
`typing_extensions`, `collections.abc`; on user questions about type hints,
Protocol, generics, NewType, PEP 695. Encodes: Protocol over ABC for ports,
`Self` for classmethod constructors, `NewType` for ID safety, PEP 695 type
aliases and generics, `Annotated` for FastAPI/Pydantic metadata, alternative
constructors via `@classmethod from_X(cls, ...) -> Self`, avoiding `Any`,
narrowing patterns.
Do NOT use for: untyped Python codebases that aren't ready to adopt type hints.
Other plugins' skills for the same job