Encodes modern Python typing idioms: Protocol over ABC, Self for classmethod constructors, NewType for ID safety, PEP 695 generics, Annotated for FastAPI/Pydantic, narrowing patterns. For typed Python 3.12+ codebases.
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.
Read when SKILL.md points to them.
Modern typed Python is a different language than typed Python five years ago. PEP 695 (Python 3.12) made generics and type aliases first-class — which is why PyStack's baseline is Python 3.12+. Protocol finally displaced ABC for most interface use cases. The Self type lets @classmethod constructors and builder-style methods type themselves correctly.
This skill encodes the idioms that hold up in 2026 typed Python.
Apply these rules whenever you're:
from_X, to_Y)Depends (the Annotated[X, Depends(...)] pattern)Protocol for interfaces; ABC only when you need shared implementationabc.ABC couples interface to inheritance. Protocol types by shape, which matches Python's duck typing and lets unrelated classes satisfy the contract without inheriting.
from typing import Protocol
class Notifier(Protocol):
async def send(self, to: str, body: str) -> None: ...
class EmailNotifier: # no Notifier in bases
async def send(self, to: str, body: str) -> None: ...
class SMSNotifier:
async def send(self, to: str, body: str) -> None: ...
async def notify(notifier: Notifier, to: str, body: str) -> None:
await notifier.send(to, body)
await notify(EmailNotifier(), "[email protected]", "hi")
await notify(SMSNotifier(), "+1...", "hi")
Use ABC only when you genuinely need partial implementation that subclasses must extend. For pure interfaces (the common case), Protocol.
Self for classmethod constructors and self-returning methodsSelf (PEP 673, Python 3.11+) lets a method return "the subclass that called me" without TypeVar ceremony.
from typing import Self
from dataclasses import dataclass
@dataclass(frozen=True, slots=True, kw_only=True)
class Money:
amount: Decimal
currency: str
@classmethod
def zero(cls, currency: str) -> Self:
return cls(amount=Decimal("0"), currency=currency)
def with_amount(self, amount: Decimal) -> Self:
return type(self)(amount=amount, currency=self.currency)
Subclassing Money keeps the type narrow: USDMoney.zero("USD") returns USDMoney, not Money.
NewType for ID safetyRaw UUID (or int, or str) lets you accidentally pass a CustomerId where an OrderId is expected. NewType creates a distinct type at type-check time with zero runtime cost.
from typing import NewType
from uuid import UUID
OrderId = NewType("OrderId", UUID)
CustomerId = NewType("CustomerId", UUID)
ProductId = NewType("ProductId", UUID)
def get_order(order_id: OrderId) -> Order: ...
customer_id = CustomerId(uuid4())
get_order(customer_id) # ty/mypy: error — CustomerId is not OrderId
Cheap at runtime; pays for itself the first time you would have shipped a swap.
Where PyStack uses it. NewType IDs are the default in framework-free code: the pure domain layer (python-pure-domain-layer), value objects, and anything else that doesn't touch SQLAlchemy. In the default SA-model style (python-aggregate-and-repo), models, repos, and services use plain Mapped[UUID] / UUID — SQLAlchemy can't map a NewType on its own:
class Order(Base):
id: Mapped[OrderId] = mapped_column(primary_key=True, default=uuid4)
# MappedAnnotationError: Could not locate SQLAlchemy Core type ... 'OrderId'
If you want typed IDs in the SA-model style too, register each one on Base and adopt it project-wide (models, repos, services, commands) — a half-converted codebase is worse than either choice:
class Base(DeclarativeBase):
type_annotation_map = {OrderId: Uuid(), CustomerId: Uuid(), ProductId: Uuid()}
TypeAlias and UnionPEP 695 (Python 3.12+) made type aliases a real statement.
# Modern
type OrderEvent = OrderPlaced | OrderCancelled | OrderRefunded
type JSON = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None
# Old (still works, but verbose)
from typing import TypeAlias
OrderEvent: TypeAlias = "OrderPlaced | OrderCancelled | OrderRefunded"
type aliases are forward-reference-safe (the RHS isn't evaluated until you ask) — no from __future__ import annotations dance needed.
TypeVarPEP 695 generics use square-bracket syntax on the class or function — no TypeVar declaration needed.
# Modern
class Repo[T]:
async def get(self, id: UUID) -> T | None: ...
async def add(self, item: T) -> None: ...
def first[T](items: Iterable[T]) -> T | None: ...
# Old
from typing import TypeVar
T = TypeVar("T")
class Repo(Generic[T]):
async def get(self, id: UUID) -> T | None: ...
Reserve old-style TypeVar only for variance you need to declare (TypeVar("T", covariant=True)); PEP 695 has its own syntax for variance.
Annotated for FastAPI Depends and Pydantic metadataAnnotated[X, metadata] attaches non-type metadata to a type. FastAPI uses it for Depends; Pydantic uses it for Field. Always prefer the Annotated form over default-argument-as-marker.
from typing import Annotated
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
router = APIRouter()
@router.get("/orders/{order_id}")
async def get_order(
order_id: UUID,
service: Annotated[OrderService, Depends(get_order_service)],
) -> OrderGet:
return await service.get(order_id)
class CreateUser(BaseModel):
email: Annotated[str, Field(min_length=5, max_length=254)]
age: Annotated[int, Field(ge=0, le=150)]
def get_order(... service: OrderService = Depends(get_order_service)) works but ages badly — the type and the metadata get separated by =, and it doesn't compose cleanly with chained metadata.
@classmethod returning SelfThe Factory Method pattern in Python is a classmethod. Name them from_<source>. The source name follows the type or origin of the data.
from typing import Self
from pydantic import BaseModel
class OrderGet(BaseModel):
id: UUID
customer_id: UUID
status: str
@classmethod
def from_model(cls, order: Order) -> Self:
return cls.model_validate(order, from_attributes=True)
class LeadGet(BaseModel):
id: int
title: str
@classmethod
def from_openai(cls, payload: dict[str, Any]) -> Self:
return cls(id=int(payload["ID"]), title=payload["TITLE"])
Don't write make_order_get(order) or convert_to_lead_get(payload) as free functions. Cohesion: the schema knows how to be built from each of its sources.
Any; if forced, isolate it at the boundaryAny disables type checking entirely. It's necessary at trust boundaries (parsing JSON, calling untyped libraries) — but it shouldn't spread.
# Bad — Any spreads through the rest of the function
def process(payload: dict[str, Any]) -> Any:
name = payload["name"] # name: Any
return name.strip() # return type: Any
# Good — Any is converted to a typed shape immediately
def process(payload: dict[str, Any]) -> str:
name: str = payload["name"]
return name.strip()
# Even better — parse with Pydantic at the boundary
class Payload(BaseModel):
name: str
def process(raw: dict[str, Any]) -> str:
return Payload.model_validate(raw).name.strip()
When you must use Any, narrow it to a typed value as soon as possible.
match or isinstance; use TypeIs for custom predicatesdef render(event: OrderEvent) -> str:
match event:
case OrderPlaced(order_id=oid):
return f"placed {oid}"
case OrderCancelled(reason=r):
return f"cancelled: {r}"
case OrderRefunded(amount=a):
return f"refunded {a}"
For custom predicates, prefer TypeIs (PEP 742) over TypeGuard — TypeIs narrows in both branches, TypeGuard only in the True branch. TypeIs is in typing from Python 3.13; on PyStack's 3.12 baseline import it from typing_extensions.
from typing_extensions import TypeIs # `from typing import TypeIs` on 3.13+
def is_str(x: object) -> TypeIs[str]:
return isinstance(x, str)
def first_str(items: list[object]) -> str | None:
for x in items:
if is_str(x):
return x # ty: x is str
return None
Final for module-level constants; Literal for discriminatorsfrom typing import Final, Literal
MAX_RETRIES: Final = 3
DEFAULT_TIMEOUT: Final = 30.0
type Status = Literal["draft", "placed", "paid", "cancelled"]
def transition(order: Order, to: Status) -> None: ...
transition(order, "placed") # ok
transition(order, "shipped") # ty: not a Literal["draft", ...]
Final prevents accidental rebinding and signals "this is a constant" to readers and to ty. Literal gives a small enum-like type without the ceremony of Enum — fine for status strings, tags, modes.
For larger sets or sets with behavior, use StrEnum.
Protocol/ABC — if you need to enforce interface usage at construction time (raise on instantiation of an abstract class), ABC does that; Protocol doesn't.Self — methods that always return a fixed concrete class (not the subclass) should name the class explicitly.NewType — identifiers you can confuse, yes; not every int is worth wrapping. In the SA-model style, only with type_annotation_map and only project-wide (rule 3).Any — at the JSON parsing boundary, before Pydantic validation. Once parsed, never again.TypeIs/TypeGuard — only needed when isinstance and match can't express the predicate. Don't reach for them by default.python-value-objects — uses NewType, Self, frozen dataclassespython-stdlib-idioms — uses Iterable[T], AsyncIterator[T] from collections.abc; tree composition with closed unions + dataclassespython-antipatterns-cheatsheet — Factory Method redirect (use @classmethod returning Self)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/pystack-python:python-typing-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-stdlib-idiomsUse when iterating over collections, building lazy pipelines, or modeling tree /
recursive structures (filesystems, ASTs, query builders, UI trees). Triggers on
imports of `itertools`, `collections.abc`; on `for ... yield ...`, `__iter__`,
generators; on tree-shaped data, leaf/composite distinctions, recursive
traversal. Encodes: generators over hand-rolled iterators, `itertools` for
composition, `AsyncIterator[T]` for async, closed unions + dataclasses for
tree shapes, recursive generators for traversal, exhaustive `match` for
visitor dispatch.
Do NOT use for: type-system idioms (use python-typing-idioms); domain
primitives (use python-value-objects); aggregates (use python-aggregate-and-repo).
Other plugins' skills for the same job