/python:codingfrom python
Use when writing or reviewing Python, covering functional design with result and record types
Ships in 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.
Code targets Python 3.15 (lazy imports, frozendict, TypeForm, t-strings, comprehension unpacking), or the lowest release its member's requires-python accepts where older (3.13 for code Blender's bundled interpreter runs). Examples use Expression, msgspec, anyio, and numpy types as standard library.
[REFERENCES]:
Parameter types state every value a function accepts and return types every outcome its caller handles:
Protocol of the operations a body reads and keep each caller's type, constraints ([S: (str, bytes)]) replace AnyStr**P captures a wrapped function's parameters, *Ts ties an argument tuple to them (Callable[[*Ts], R]), *args: object erases bothProtocol types a callable Callable cannot spell (keyword parameters, __name__, overloads) beside the consumer reading itProtocol of the members a body reads, a module constant as a @property member/ parameters, a value a caller varies is a keyword-only * parameter, required unless an owner states its defaultField combines optype's multiplication and reflected-subtraction protocols, and smoothstep preserves its scalar or array argument's type:
class Field(optype.CanMulSame[float], optype.CanRSubSelf[float], Protocol): ...
def smoothstep[V: Field](values: V, /) -> V:
return values * values * (3.0 - values * 2.0)
Functions are total when each declared input produces a declared output, with no exception or None their signature omits. Functions failing on part of their input narrow it to a validated type or widen output to Option[T] or Outcome[T]:
int -> Tier is incomplete when some integers fail validation, Quantity -> Tier over a record validating at construction covers every valuemin, max, and next raise on empty input, max(items, default=...) and next(iter(items), default) make empty reads totalT | None appears where an external API speaks it, option.of_optional converts it at the readmatch, isinstance, or a TypeIs predicatebool parameter holds dataPure functions compute their result from arguments alone with no side effect, and the result can replace the call. Mutating a local that stays in its function is no side effect:
def expired(now: datetime, issued: datetime, lifetime: timedelta) -> bool)(), frozenset(), frozendict(), NOTHING, a frozen record)(State, Event) -> State)functools.cache memoizes a pure top-level function or a zero-argument builder, a cached method keeps every self it receives aliveHigher-order functions take or return a function and own fixed control flow, their caller supplies the varying rule. Bind each varying part through partial over a top-level function:
map(str.strip, lines), reduce(Box.merged, boxes))str.casefold)read owns the catch and its fault once, and each reader is a partial over the function it applies, partial(read, Path.read_text) for text:
def read[T](reader: Callable[[Path], T], path: Path, /) -> Outcome[T]:
caught: Callable[[Path], Result[T, OSError]] = catch(reader, exception=OSError)
return caught(path).map_error(partial(Fault.of, Reason.UNREADABLE, path))
content: Callable[[Path], Outcome[bytes]] = partial(read, Path.read_bytes)
Build a returned value in one expression (a comprehension, conditional expression, or record constructor):
tuple, frozenset, or frozendict from every arm, a generator stays where laziness bounds memoryOption values flatten through to_list() (tuple(*o.to_list() for o in options)), bind(identity) flattens a nested Optionsum(terms, start=zero) over numbers and arrays, math.prod, math.fsum, "".joina.items() ^ b.items() holds every differing pair, a.keys() - b.keys() every key b lacksmatch, a table, or a relation in place of an extracted helperComprehension unpacking flattens each element's parts into one collection, and a walrus binds what a filter tests and the element reads:
def keys(pattern: re.Pattern[str], lines: Iterable[str], /) -> frozenset[str]:
return frozenset(*hit.groups() for line in lines if (hit := pattern.fullmatch(line.strip())))
Pattern matching selects a result by a value's type, shape, or fields, and keeps extraction, guards, and results together. toggled derives each transition from the case it receives:
type Watch = Running | Paused
def toggled(watch: Watch, at: datetime, /) -> Watch:
match watch:
case Running(since=since, total=total) if at > since:
return Paused(total=total + (at - since))
case Paused(total=total):
return Running(since=at, total=total)
case _:
return watch
Running holds since and total, Paused holds total, and a toggle at or before since returns watch unchanged:
kw_only record or a pydantic model has empty __match_args__| alternatives share an arm when each binds the same names (case Running(total=total) | Paused(total=total):)[first, *rest]) bind rest as a list and match no str or bytes, case (only,): proves exactly onecase (first, *rest): return sum(rest, first) folds a non-empty sequence with no zero sentinel{"key": float(value), **rest}) decode each key once, dotted value patterns (Color.RED) compare memberscase _:, a guarded arm or a tuple subject ends in case _:case _: returning an ErrorDomain values no language or package type (datetime, Path, ndarray) states are frozen msgspec.Struct records: slotted, hashable, matchable. Fields state constraints as Meta bounds every decode enforces, a type alias names each bounded domain, and behavior is a method or property. Ramp bounds each stop and the stop count, checks stop order in __post_init__, and derives a value no field stores:
type Unit = Annotated[float, msgspec.Meta(ge=0.0, le=1.0)]
type Positive = Annotated[float, msgspec.Meta(gt=0.0)]
class Ramp(msgspec.Struct, frozen=True, kw_only=True):
stops: Annotated[tuple[tuple[Unit, Positive], ...], msgspec.Meta(min_length=2)]
def __post_init__(self) -> None:
if any(start >= end for (start, _), (end, _) in pairwise(self.stops)):
raise ValueError(self)
@property
def slopes(self) -> tuple[float, ...]:
return tuple((high - low) / (end - start) for (start, low), (end, high) in pairwise(self.stops))
msgspec.json.decode(raw, type=Ramp) refuses a stop outside its bound or a lone stop with the refused key path ($.stops[1][0]):
tuple[Unit, Positive]), parts read by name are record fieldsMeta validates decoding and raw-value conversion; constructors and Annotated parameters do not enforce Meta bounds__post_init__ raises ValueError for cross-field invariants on new records; convert reuses matching records unchangedOutcome[Self]tuple[T, ...], frozenset[T], frozendict[K, V], a frozen record), hashing a record hashes every fieldOption[T] property over a decoded T | None fieldmsgspec.structs.fields and msgspec.inspect serve a codec alonefunctools.cached_property on a record needs dict=Truehash() salts str and bytes per process, and keys that outlive a process hash a deterministic encodingpython:msgspec for msgspec records and codecsModel each state a consumer inspects as its own case, and states differing only by a value as one record of that value. Counting a type's values (a product multiplies its fields' counts, Option[T] adds one) exposes unneeded states. One tagged base serves every record union in a package, and a callable tag derives each wire tag from its class name. Operations over every case are one function with one match:
class Case(msgspec.Struct, frozen=True, kw_only=True, tag_field="kind", tag=str.lower): ...
class Circle(Case, frozen=True, kw_only=True):
radius: Positive
class Rect(Case, frozen=True, kw_only=True):
width: Positive
height: Positive
type Shape = Circle | Rect
def area(shape: Shape, /) -> float:
match shape:
case Circle(radius=radius):
return math.pi * radius**2
case Rect(width=width, height=height):
return width * height
msgspec.json.decode(raw, type=tuple[Shape, ...]) dispatches each element by kind in one pass, and math.fsum(map(area, shapes)) sums them:
Shape alias, and a new case adds its arm to every match over itfrozen=True and kw_only=TrueBehavior derives from a declaration read once at import, callers state what the declaration cannot. Closed value sets are one enum, and each rule-derived fact is a property over a member's value:
class Tier(IntEnum):
FREE = auto()
TEAM = auto()
SCALE = auto()
@property
def quota(self) -> int:
return 1 << (10 * self.value)
Tier.TEAM.quota is 1 << 20, and a new member takes every fact from its rank:
StrEnum with auto() takes each wire token from its member name, an explicit value holds a datum consumers read (a template)__name__bpy.path.display_name(<key>) in Blender), a name= literal restating it__init_subclass__ and __set_name__Fallible functions return a result type, one type per concern:
| [INDEX] | [TYPE] | [CONCERN] |
|---|---|---|
| [01] | Option[T] | Absence without a reason |
| [02] | Outcome[T] | Expected failure with reasons, first failure stops |
Input boundaries select the result type and functions keep it. One boundary converts it through the member named for its target (to_result_with, to_option, option.of_optional, to_optional):
default_value and default_with supply a default the domain defines for absence or failuretuple is a result, Option[tuple[T, ...]] exists only where a consumer treats no collection and an empty one apartError through every producer, NOTHING holds absence alonepython:expression for expression membersExceptions mark a violated precondition or a third-party raise a boundary converts. One Fault record serves every package, its reason an enum member holding the message template, and message renders each held value once by its kind. Fault.of returns the non-empty tuple every fault builder needs:
type Faults = tuple[Fault, *tuple[Fault, ...]]
type Outcome[T] = Result[T, Faults]
class Reason(StrEnum):
ABSENT = "{subject} holds no {member}"
INVALID = "{subject} is invalid. {cause}"
OUTSIDE = "{subject} accepts {member}, not {cause}"
UNREADABLE = "{subject} is unreadable. {cause}"
UNWRITABLE = "{subject} is unwritable. {cause}"
EXPIRED = "{subject} exceeded {cause}"
FAILED = "{subject} failed. {cause}"
def shown(value: object, /) -> str:
match value:
case str():
return value
case os.PathLike():
return os.fspath(value)
case tuple():
return shlex.join(map(str, value))
case type():
return value.__qualname__
case _:
return reprlib.repr(value)
class Fault(msgspec.Struct, frozen=True, kw_only=True):
reason: StrEnum
subject: object
member: object = ""
cause: object = ""
@property
def message(self) -> str:
return self.reason.format(subject=shown(self.subject), member=shown(self.member), cause=self.cause)
@classmethod
def of(cls, reason: StrEnum, subject: object, cause: object = "", /, *, member: object = "") -> Faults:
return (cls(reason=reason, subject=subject, member=member, cause=cause),)
reason takes a member of any package's reason enum, with one member and its template per failure a consumer handles apart:
subject holds the refused value and member the member or bound it misses, each as its value, and a caught exception stays as causestr, repr, or shlex.join around it restating shown{count:,}, {ratio:.2%}), quantities through pint's ~P, and durations as their timedeltapartial(Fault.of, <reason>, <subject>) serves map_error and filter_with with the refused value as cause, and to_result_with with nonereason member or by a class pattern on its causeError or a Result holding the degraded valuecatch(f, exception=E)(arguments) from expression.extra.result covers one raising call and passes the callable itself. ran keeps native launch and exit exceptions as its fault cause:
def ran(program: str, /, *args: str, stdout: int | None = None) -> Outcome[subprocess.CompletedProcess[bytes]]:
try:
return Ok(subprocess.run((program, *args), stdout=stdout, check=True))
except (OSError, subprocess.CalledProcessError) as error:
return Error(Fault.of(Reason.FAILED, (program, *args), error))
Overloaded calls take a typed def under @catch, and calls raising unrelated classes take a try.
Give each step a function, and select its operator by signature and by whether steps depend on each other:
| [INDEX] | [SIGNATURE] | [OPERATOR] | [BEHAVIOR] |
|---|---|---|---|
| [01] | T -> R | .map | Transforms a present value, keeps the result type |
| [02] | T -> bool on Result | .filter_with | Keeps a passing value, else fails with built faults |
| [03] | T -> bool on Option | .filter | Keeps a passing value, else empties it |
| [04] | T -> Result[R, E] | .bind | Continues with a dependent step, first failure stops |
| [05] | E -> F | .map_error | Translates a failure into package faults |
| [06] | E -> Result[T, E] | .or_else_with | Recovers one failure shape, else keeps the faults |
| [07] | Option[T] -> Result[T, E] | .to_result_with(f) | Promotes absence where its reason is known |
| [08] | Independent results | paired, accumulated | Keeps every value, or every fault in input order |
Checks reading a value alone are Meta bounds or __post_init__ on its record, and chains hold checks reading a runtime value (a limit, a held set). Independent checks combine through paired:
def accepted(limit: int, taken: frozenset[str], entry: Entry, /) -> Outcome[Entry]:
return paired(
Ok(entry.size).filter_with(lambda size: size <= limit, partial(Fault.of, Reason.OUTSIDE, "size", member=f"at most {limit}")),
Ok(entry.name).filter_with(lambda name: name not in taken, partial(Fault.of, Reason.OUTSIDE, "name", member="an unused name")),
).map(lambda _: entry)
Entry is a record of name and size, and an entry over the limit with a taken name fails with both faults:
reduce(lambda held, item: held.bind(lambda state: step(state, item)), items, Ok(seed)) folds dependent steps until the first refused item-> Outcome[T]filter_with, to_result_with, Some(x).filter)Values stay inside a result through a pipeline, and the entry point reads it once through match. Unix commands map reasons to native sysexits statuses:
EXITS: frozendict[StrEnum, int] = frozendict({
Reason.ABSENT: os.EX_DATAERR,
Reason.INVALID: os.EX_DATAERR,
Reason.OUTSIDE: os.EX_DATAERR,
Reason.UNREADABLE: os.EX_NOINPUT,
Reason.UNWRITABLE: os.EX_CANTCREAT,
Reason.EXPIRED: os.EX_TEMPFAIL,
Reason.FAILED: os.EX_UNAVAILABLE,
})
def exited(outcome: Outcome[int], /) -> int:
match outcome:
case Ok(code):
return code
case Error((Fault(cause=subprocess.CalledProcessError(returncode=code)) as fault,)):
sys.stderr.write(f"{fault.message}\n")
return code
case Error(faults):
sys.stderr.writelines(f"{fault.message}\n" for fault in faults)
return EXITS[faults[0].reason]
EXITS maps every reason the command's packages raise to its sysexits status. A lone failed child exits with its own status, other faults with the first fault's reason status, and a reason with no row raises KeyError as a defect.
Decode external bytes or builtins in one typed call through msgspec.<format>.decode(raw, type=T) or msgspec.convert. Module-level codecs hold a fixed type or decoder-only options (JSON float_hook). TypeForm[T] parameters accept any type form, a type alias over Annotated included, and type the result as T:
def stored[T](form: TypeForm[T], path: Path, /) -> Outcome[T]:
decode: Callable[[bytes], Result[T, msgspec.DecodeError]] = catch(msgspec.json.Decoder(form).decode, exception=msgspec.DecodeError)
return content(path).bind(lambda raw: decode(raw).map_error(partial(Fault.of, Reason.INVALID, path)))
stored(Ports, path) over type Ports = tuple[Annotated[int, msgspec.Meta(ge=1, le=65535)], ...] reads as Outcome[tuple[int, ...]]:
partial(stored, Ports) is the reader of one file kindDecodeError covers malformed input and its subclass ValidationError a schema mismatchtomllib, ast, string.Formatter().parse, a markdown parser)python:pydantic for validation that reports every error at once or publishes a schemaInject a snapshot value, an on-demand function, or a Protocol each platform implements in full. Handle owners needing field-level equality or representation exclusions use frozen dataclass records with field(compare=False, repr=False). Prefer generated dataclass initialization when declared fields express the constructor. Custom constructors initialize frozen dataclass fields, including inherited fields, with object.__setattr__; ordinary frozen field assignment raises FrozenInstanceError. Dynamic host writes use setattr for native __setattr__ dispatch. Scopes yield acquisition results:
@catch(exception=OSError)
def _entered(stack: ExitStack, paths: Sequence[Path], /) -> tuple[BufferedReader, ...]:
return tuple(stack.enter_context(path.open("rb")) for path in paths)
@contextmanager
def opened(paths: Sequence[Path], /) -> Generator[Outcome[tuple[BufferedReader, ...]]]:
with ExitStack() as stack:
yield _entered(stack, paths).map_error(partial(Fault.of, Reason.UNREADABLE, tuple(paths)))
Failed opens release every stream opened before them at scope exit, and the body receives one fault in place of an exception:
@contextmanager and @asynccontextmanager return Generator[T] or AsyncGenerator[T], and ExitStack owns every releasepython:telemetry for logs, traces, and measurementsConcurrent regions are anyio task groups, tasks return results that cancel no sibling on an expected failure, and exception groups hold defects. catch and bind span no await, and an async def holds an awaited raising call in try and returns Error from its handler:
async def loaded(path: anyio.Path, /) -> Outcome[bytes]:
try:
data = await path.read_bytes()
except OSError as error:
return Error(Fault.of(Reason.UNREADABLE, path, error))
return Ok(data)
await anyio.amap(loaded, paths) returns each path's outcome in input order, a missing file's fault beside its siblings' bytes:
anyio.Path, anyio.open_file, anyio.run_process, anyio.sleep)except* handlers hold no return, a handler binds the fault and the function returns it after the tryInstants are aware datetime values and durations are timedelta values, in fields, parameters, and arithmetic alike. Instant refuses a naive value at decode, and Lease computes from a now its caller reads once:
type Instant = Annotated[datetime, msgspec.Meta(tz=True)]
class Lease(msgspec.Struct, frozen=True, kw_only=True):
issued: Instant
lifetime: timedelta
def left(self, now: datetime, /) -> timedelta:
return max(self.issued + self.lifetime - now, timedelta())
Lease decodes lifetime from an ISO 8601 duration (PT1H):
timedelta in place of a number with a unit suffix, delta / timedelta(seconds=1) hands a numeric API its floatdelta // step counts whole steps and delta % step returns the rest, exact to the microsecondZoneInfo subtract as wall clocks (1 day across a 23-hour DST day), elapsed spans subtract in UTCtime.monotonic_ns(), anyio.current_time()) no wall clock adjustment movesEach module holds one owner, and imports point down its layers, absolute from its package root:
import msgspec
lazy from expression import Ok
lazy import numpy as np
lazy from signals import Outcome
class Window(msgspec.Struct, frozen=True, kw_only=True):
width: int
def smoothed(window: Window, values: np.ndarray, /) -> Outcome[np.ndarray]:
return Ok(np.convolve(values, np.full(window.width, 1 / window.width), mode="same"))
msgspec loads with the module for the base Window reads, numpy and Ok load at the first call, and Outcome at the first read of the function's annotations:
import <module> read through attributes or from <module> import <names>np)msgspec.Struct)__init__.py is its entry: a docstring, one import per private module of its public names, and __all___, siblings import them by that path and re-export nothing__all__, names one file alone reads take _ and leave every __all__annotationlib.get_annotationsto_process and to_interpreter workers re-import themblender:coding for imports under Blender's Python 3.13python:cyclopts for command-line applicationspython:document for docstringswriting:prose for names, messages, and descriptionslazy binds a proxy and loads its module at the first read of the name, a saving only for a module nothing loads at startup or import time (sys, os, abc, a module an eager import loads):
msgspec.Struct, dataclass, NamedTuple), and those names reify theretype alias values reify at their first readlazy import a.b.c binds a, and a read of a.b.c.X loads a, a.b, then a.b.clazy statement, and each later read retrieslazy imports raise SyntaxError inside try, a function, or a class body, and as lazy from <module> import *lazy import in place of a TYPE_CHECKING block-X lazy_imports=all and sys.set_lazy_imports_filter set process policy at an application entry point, never in a librarypython -X importtime prints each module's self and cumulative microseconds after its children, a lazy import under the read that reified itModules a value names at runtime load through the standard library member owning their case:
| [INDEX] | [CASE] | [MEMBER] |
|---|---|---|
| [01] | Module name | importlib.import_module(name), package= for a relative name |
| [02] | <module>:<attribute> | pkgutil.resolve_name |
| [03] | Installed plugin | importlib.metadata.entry_points(group=<group>), then EntryPoint.load |
| [04] | Package data file | importlib.resources.files(<module>).joinpath(<part>, ...) |
| [05] | Platform module | Module-level if sys.platform == "<platform>": branch |
importlib.util.find_spec("<package>.<module>") runs the package's __init__.py, a top-level name alone probes without importimportlib.util.LazyLoader defers a module a runtime value names, lazy covers every name the source spellsimportlib.reload re-executes into the same module object, and names a from import bound keep their old objects--platform value alone and under ty for every platform python-platform = "all" selectsreferences/boundaries.md (opens in a new tab)references/concurrency.md (opens in a new tab)references/decorators.md (opens in a new tab)references/functions.md (opens in a new tab)references/numerics.md (opens in a new tab)references/records.md (opens in a new tab)references/results.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
8 skills in this plugin
/cycloptsUse when writing or reviewing a cyclopts app, covering commands, parameters, user classes, meta apps, configuration, completion, and exit codes/debuggingUse when debugging Python at runtime (failing test, wrong value, swallowed exception, hang, crash, slow or growing process), covering debugpy environments, pytest stops, exception filters, attaches through pdb, and the interpreter's stack, fault, and profiling tools/documentUse when writing or reviewing Python docstrings or fixing ruff D or DOC findings, covering scope and Google-style syntaxOther plugins' skills for the same job
npx claudepluginhub bsamiee/rasm --plugin python