/omniagents-python:typingsfrom omniagents-python
Use when writing or reviewing Python 3.14+ with strict type-safety enforced: generics with PEP 695 syntax, annotationlib / deferred annotations, Protocol vs ABC, ParamSpec decorators, TypeIs / TypeGuard narrowing, TypedDict / ReadOnly, magic strings / numbers vs Literal / StrEnum / Final, NewType vs aliases, domain IDs vs bare str/int primitives (primitive obsession), or any time mypy / pyright / pyrefly / ty is configured, run, or failing.
Ships in omniagents-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.
This project maintains a strict-by-default type-safety bar across every
configured type checker. The exact set is recorded in the consuming project's
tooling config (commonly mypy, pyright, pyrefly, ruff, ty, and a typecheck
target); what matters here is the rule, not the inventory. The cost of a
single Any leak compounds: types decay outward from the leak site,
mechanical refactors become exploratory, and bugs that should fail at the
boundary surface in unrelated modules.
This skill assumes Python 3.14+. It uses the modern syntax and semantics
from PEP 695, PEP 696,
PEP 705, PEP 742,
PEP 649, and PEP 749.
The canonical examples in references/canonical-examples.md show accepted
shapes; the decision table in references/decision-trees.md handles common
trade-offs.
This skill is rules, not a tutorial. It assumes familiarity with TypeVar,
Protocol, ParamSpec, TypeGuard, TypeIs, TypedDict, Annotated,
and NewType. It specifies which patterns projects using this skill have
chosen and which they have rejected.
uv run mypy, uv run pyright, uv run pyrefly,
uv run ty check) or together through the project typecheck target. The set of checkers may grow; the bar does not.# type: ignore requires both an error code and an inline reason:
# type: ignore[arg-type] # third-party stub missing field X. Bare
# type: ignore is rejected on review.Any is forbidden in internal code. It is permitted only at I/O boundaries
such as CLI parsing, JSON ingest, and untyped third-party APIs, and only
with a comment explaining the leak.Any, or # type: ignore your way out.Self from PEP 673 for fluent,
builder, and classmethod constructors that return the current class.
When annotating cls explicitly in a classmethod, write
cls: type[Self], not cls: type[BaseClass]; the latter breaks subclass
return inference.
String-quoted forward references like -> "QueryBuilder" are forbidden in
new code.from __future__ import annotations just for forward
references. Python 3.14 uses deferred annotation evaluation by default
under PEP 649 and
PEP 749. Plain forward references in
annotations no longer need string quoting.annotationlib. Code that reads
annotations at runtime must use
annotationlib.get_annotations()
or typing.get_type_hints()
deliberately. Choose annotationlib.Format.VALUE, FORWARDREF, or
STRING based on whether unresolved names should raise, become
ForwardRef values, or remain source strings.__annotations__ internals directly. Python 3.14 changed
the runtime model for annotations; direct reads are easy to get wrong when
annotations are deferred or contain unresolved imports.TYPE_CHECKING only to avoid runtime imports. Undefined symbols in
annotations are harmless until annotation introspection evaluates them, but
static checkers still need imports guarded by if TYPE_CHECKING: when a
type lives in an expensive or cyclic module.class Registry[KeyT, ValueT]: and
def first[ItemT](items: Iterable[ItemT]) -> ItemT | None: are mandatory.
Module-level TypeVar / ParamSpec declarations followed by Generic[T]
subclassing are rejected when ruff UP046 / UP047 are enabled. The legacy
form is permitted only in .pyi stubs, vendored third-party code, and the
rare Protocol variance cases called out in references/decision-trees.md....T suffix. Prefer KeyT, ValueT,
ItemT, ReturnT, InputT, and OutputT over bare T, K, V, or R.
Single-letter names are reserved for ParamSpec (**P) and variadic type
parameters (*Ts) when the conventional form is clearer.TypeVar, ParamSpec, and TypeVarTuple are appropriate
when the default preserves the obvious common case. Do not use defaults to
hide ambiguous APIs or to make partial specialization harder to see.Protocol for public and
plugin-facing contracts where independent implementations should satisfy a
structural shape. Use an ABC when shared default behavior, nominal
registration, or runtime subclass checks are part of the design. Do not add
either for one-off internal code when a concrete type is clearer.@runtime_checkable only when isinstance is genuinely needed. Protocol
conformance is a static check by default; runtime-checkable Protocols are
for plugin loaders and dynamic dispatch, not the default decoration.collections.abc generics. Import Callable, Iterable,
Iterator, Generator, AsyncGenerator, Mapping, Sequence, and
similar ABCs from collections.abc, not deprecated aliases in typing.Generator / AsyncGenerator for context-manager return types.
@contextmanager functions return Generator[YieldT]; @asynccontextmanager
functions return AsyncGenerator[YieldT]. Python 3.13+ defaults the send
and return type parameters, so avoid noisy Generator[YieldT, None, None]
unless a checker or public API requires it.ParamSpec for decorators that wrap user callables. Anything preserving
the wrapped function's call signature uses ParamSpec:
def traced[**P, ReturnT](fn: Callable[P, ReturnT]) -> Callable[P, ReturnT].
Plain Callable[..., Any] decorators are forbidden in typed package code.TypeIs before TypeGuard. Use
TypeIs
from PEP 742 for sound
isinstance-style predicates because it narrows both true and false
branches. Use TypeGuard only when the narrowed type is not a subtype of
the input type or the negative branch cannot be narrowed safely.context: dict[str, object] to the base.
Bare-string Exception subclasses are reserved for genuinely contextless
failures.pydantic.BaseModel for structured values that benefit from
validation, defaults, serialization, or an explicit schema, including but not
limited to I/O boundaries. TypedDict is for values that must remain
dict-shaped, such as typed **kwargs, JSON-like payloads, or interop with
mapping APIs. Use @dataclass only for lightweight internal records where
Pydantic behavior would add no value. Plain classes are fine when behavior,
invariants, or construction rules matter more than record syntax.ReadOnly
for immutable TypedDict keys. A TypedDict field that consumers must not
mutate should be annotated with ReadOnly[...] from
PEP 705. Remember this is enforced by
type checkers, not at runtime.uv is the only Python invoker. Use uv run mypy, uv run pytest,
uv run python .... Never use bare python or pip.type statement. Use type UserId = str,
type Cache[KeyT, ValueT] = OrderedDict[KeyT, tuple[ValueT, float]], and
recursive aliases such as type JSONValue = str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]. Module-level
X: TypeAlias = ... is rejected in new code.NewType for domain identifiers that cross signatures. The checker
must distinguish whenever two same-shape primitives could be swapped at a
call site — ids, tokens, bucket and key names — and the cheapest sound
distinction is BucketName = NewType("BucketName", str) with identical
runtime representation. The openai-python SDK types every domain id this
way (FileId, BatchId). A type X = str alias carries zero static
information: it names a primitive, it does not type it — use an alias
only when any str is genuinely acceptable and the name is pure
readability. NewType is the static half of the contract; runtime
validation of untrusted input at the boundary is the dynamic half.
Neither replaces the other, and "runtime validation is the entire
point" is a false choice.StrEnum / IntEnum for closed string and integer sets. Module-level
string constants describing one closed set collapse into a StrEnum
subclass with auto(). Use IntEnum for numeric protocol codes and
Flag / IntFlag when bitwise combination is the point.Literal[...] for ad-hoc closed sets in one signature. Promote to
StrEnum the moment the same set appears in a second signature.str parameter fed only bare literals is an unlabeled closed set.
Closed sets rarely arrive as declared constants; they enter the code as
inline strings at call sites — step names, states, modes, kinds, event
names — feeding a parameter typed str
(record("result_probe"), publish(state="failed")). That parameter's
real contract is the closed set: type it Literal[...] or StrEnum so a
typo is a checker error instead of a silent runtime miss. Test seams,
instrumentation hooks, and log/metric labels are not exempt.code=str(ErrorCode.DEADLINE_EXCEEDED) into a code: str parameter
erases the closed set the enum exists to enforce. The signature takes the
enum type (or a union of enum types); conversion to str happens once, at
the serialization boundary.LiteralString from PEP 675 for
SQL, shell, and format-string parameters. Functions that compose user
input into queries or commands take LiteralString, not str, so the
checker rejects untrusted strings at the call site.@override from PEP 698 on every
override. Pyright flags missing decorators in strict mode. The decorator
catches silent drift when a base method is renamed and the override
accidentally becomes a new method.Annotated[T, ...] for typed metadata. Pydantic Field, Typer
Option / Argument, and validation or serialization hints must travel
alongside the type. Prefer Annotated[int, Field(ge=0)] over
x: int = Field(ge=0).Final for module-level constants and class attrs not meant to be
reassigned. Use MAX_RETRIES: Final = 3 and
Final[frozenset[str]] for immutable container constants. Inline numeric
literals with semantic weight — timeouts, caps, retry budgets, thresholds,
protocol codes — are promoted to named Final constants; identity values
and unit conversions (0, 1, * 1000) stay inline. But a constant
whose value is configuration — anything an operator would want to
override, inspect, or vary per environment — belongs in the project's
pydantic Settings tree (see the pydantic skill, § Settings), not in
another module constant. A default stated in two places (a signature
default and a config field, or two modules) has already drifted: one
owner, and signatures reference it.assert_never in unreachable exhaustive branches. A new variant added
to a discriminated union must break the build at every case _: or final
else, not silently fall through at runtime._as_str /
_as_int / _as_optional_int helpers narrowing object-typed payloads —
including the isinstance(x, int) and not isinstance(x, bool) dance — is
a hand-built validator. If the goal is narrowing for the checker only, it
is a TypeIs predicate. If the goal is parsing an untrusted payload, it
is a pydantic TypeAdapter or boundary model (see the pydantic skill,
§ TypeAdapter): strict int-not-bool behavior, declared shapes, and error
paths come free instead of being re-derived per helper.value or "", a sentinel default such
as datetime(1970, 1, 1), or 0 substituted for a missing count invents
data indistinguishable from the real thing. Model the field T | None
and make absence explicit at the consumer.type alias. type BucketName = str
reads like a domain type and checks like str. If the name deserves to
exist, it deserves NewType; if any str is genuinely fine, the alias is
a costume — inline the primitive.references/decision-trees.md - lookup
pairs for ABC vs Protocol, bounded vs constrained type variables, Literal
vs StrEnum, TypeGuard vs TypeIs, and related choices.references/canonical-examples.md -
strict examples for Registry, Protocol, ParamSpec decorator, narrowing,
error hierarchy, builder, overload, aliases, NewType, StrEnum,
discriminated union, and Annotated + Pydantic.typing docs
and Python 3.14 annotationlib docs
are the runtime references. PEPs are historical design records; prefer the
current docs when they disagree.This skill is project policy, not a complete upstream reference. When applying it to unfamiliar APIs, version-sensitive behavior, tool/checker disagreement, or anything that may have changed since the skill was written, verify current behavior against primary docs. Prefer Context7 MCP when available. If it is unavailable, use web search restricted to official sources.
Primary sources:
.ruff.toml / pyproject.toml, .mypy.ini,
pyrightconfig.json, and the task runner or Makefile.What SKILL.md sets; muted values are Claude Code's defaults
Trigger for Python files, pyproject typing configuration, strict checker failures, type annotation design, runtime annotation introspection, PEP 695 generics, PEP 696 defaults, PEP 705 ReadOnly TypedDict keys, PEP 742 TypeIs predicates, PEP 649 / PEP 749 deferred annotations, decorator signatures, Protocol boundaries, NewType identifiers, enum/literal choices, magic-string and magic-number promotion, stringly-typed parameters, isinstance coercion helpers, bare-primitive parameters needing domain IDs, or public API typing reviews.
inheritbashnpx claudepluginhub gao-hongnan/omniagents --plugin omniagents-python6 skills in this plugin
/docstringsUse when writing or reviewing Python docstrings for public modules, classes, functions, methods, properties, generators, overloads, doctest examples, or generated Sphinx API documentation, especially when choosing NumPy vs Sphinx style or deciding which Parameters, Returns, Yields, Raises, Warns, Attributes, Notes, See Also, and Examples sections belong./library-patternsUse when writing or reviewing Python that wraps a network service or authors a client SDK: client construction, async lifecycle, granular timeouts, retry policy, idempotency keys, structured exception hierarchies, per-request overrides, structured outputs with Pydantic, streaming via async context managers, request-id propagation, or pagination./Other plugins' skills for the same job