Catalogue / typed-python-workbench
typed-python-workbench
Older skill: source not recordedSignedWrites and reviews Python 3.11+ code with typed transformations, data contracts, Pydantic v2 boundaries, resource management, and focused tests. Use when asked to "refactor a Python function", "add type hints", "validate API models with Pydantic", "write a generator or context manager", "set up pyte…--- name: typed-python-workbench description: >- Writes and reviews Python 3.11+ code with typed transformations, data contracts, Pydantic v2 boundaries, resource management, and focused tests. Use when asked to "refactor a Python function", "add type hints", "validate API models with Pydantic", "write a generator or context manager", "set up pytest cases", or "review this .py file". Not for installing packages or switching interpreters without a stated project scope, for other languages, or for overriding a project's own style guide. ---
Typed Python Workbench
Review the boundary first
Before creating or editing Python code, inspect its purpose, callers, interpreter, dependencies, tests, and file conventions. On resuming a task, repeat the type/model/tool checks for the files actually being changed; no separate plugin command is required.
An explicit request authorizes its named edit or isolated test scope. Confirm additional package installs, interpreter/environment changes, formatter fixes outside that scope, overwrites, and external service calls before doing them.
| Boundary | Representation | What it supplies | |---|---|---| | Untrusted API request/response | Pydantic BaseModel | Runtime validation and serialization | | Already-validated external dictionary shape | TypedDict | Static keys/types only | | Internal record | dataclass | Generated constructor/equality and explicit defaults | | Environment-derived config | pydantic-settings | Approved environment scope and typed settings | | Iteration interface | Iterable, Iterator, Sequence, Mapping | Declare only the capabilities the function needs |
Type annotations alone do not sanitize external input. Pydantic coercion is a policy choice; use strict models where coercion would conceal an error. Validate before treating raw JSON as a TypedDict.
Syntax choices with concrete replacements
| Need | Fragile form | Prefer | |---|---|---| | Visit items | for i in range(len(rows)): use(rows[i]) | for row in rows: use(row) | | Index plus item | Update a separate counter | for index, row in enumerate(rows, start=4): ... | | Equal-length pairing | Silent zip truncation | zip(labels, minutes, strict=True) | | Reverse traversal | Copy then reverse | reversed(rows) for a reversible sequence | | Sorted traversal | Assume no allocation | sorted(rows) returns a new list; measure memory | | Default lookup | Membership then indexing | mapping.get(key, default) | | Key/value traversal | Index for every key | for key, value in mapping.items(): ... | | Swap | Temporary assignment chain | left, right = right, left | | Build text | Repeated string concatenation | " / ".join(parts) | | Many membership checks | Repeated long-list search | Build a set once if values are hashable | | Resource lifetime | Manual close on one branch | with or a closing/context adapter | | Empty container | len(rows) > 0 | if rows: | | Missing sentinel | value == None | value is None |
Comprehensions are useful for simple selection/transformation. Keep a normal loop for multi-step logic, side effects, complex error handling, or readability. A generator saves intermediate storage; consuming it into a list still allocates.
labels = ["clay", "ink", "glass"]
lengths = {label: len(label) for label in labels}
selected = [label.upper() for label in labels if len(label) > 3]
energy = sum(number * number for number in range(240))
any_long = any(len(label) > 4 for label in labels)
domains = {address.rsplit("@", 1)[-1] for address in ["inez@example.org", "noel@example.net"]}
settings: dict[str, object] = {"port": 8123}
port = settings.get("port", 8124)
groups: dict[str, list[str]] = {}
for label in labels:
groups.setdefault(label[0], []).append(label)
merged = {"debug": False} | {"debug": True}
unpacked = {**{"timeout": 8}, **{"timeout": 12}}
first, *remaining = labels
left, right = 3, 8
left, right = right, left
assert (first, remaining, left, right) == ("clay", ["ink", "glass"], 8, 3)Use meaningful names, small functions, composition before inheritance, pathlib.Path, logging for operational messages, and explicit imports. Document a file's role with a module docstring; retain project-specific header conventions if required.
Complete typed standard-library module
Save the following as workshop_core.py in the requested scope. All capabilities are inline. No service is called and no filesystem data is read on import.
"""Typed local transformations for a workshop schedule; no external I/O on import."""
import logging
import time
from collections import Counter, defaultdict, deque, namedtuple
from collections.abc import Callable, Generator, Hashable, Iterable, Iterator, Mapping, Sequence
from contextlib import ExitStack, closing, contextmanager, suppress
from dataclasses import dataclass, field
from enum import Enum, IntEnum, StrEnum, auto
from functools import cached_property, lru_cache, partial, wraps
from itertools import chain, combinations, groupby, islice, permutations, product
from pathlib import Path
from typing import ClassVar, NotRequired, ParamSpec, Required, TypeVar, TypedDict
T = TypeVar('T')
K = TypeVar('K', bound=Hashable)
V = TypeVar('V')
P = ParamSpec('P')
R = TypeVar('R')
logger = logging.getLogger(__name__)
def numbered(values: Sequence[T], start: int = 1) -> list[tuple[int, T]]:
return list(enumerate(values, start))
def paired(labels: Sequence[str], durations: Sequence[int]) -> list[tuple[str, int]]:
return list(zip(labels, durations, strict=True))
def joined(*streams: Iterable[T]) -> list[T]:
return list(chain.from_iterable(streams))
def first_n(stream: Iterable[T], count: int) -> list[T]:
if count < 0: raise ValueError('count must not be negative')
return list(islice(stream, count))
def sorted_groups(values: Iterable[T], key: Callable[[T], str]) -> dict[str, list[T]]:
# groupby combines adjacent equal keys, so sort first when global grouping is intended.
return {label: list(group) for label, group in groupby(sorted(values, key=key), key=key)}
def lookup(values: Mapping[K, V], key: K, default: V) -> V:
return values.get(key, default)
def buckets(pairs: Iterable[tuple[K, V]]) -> dict[K, list[V]]:
grouped: defaultdict[K, list[V]] = defaultdict(list)
for key, value in pairs: grouped[key].append(value)
return dict(grouped)
def frequencies(values: Iterable[K]) -> dict[K, int]:
return dict(Counter(values))
def overlaid(*maps: Mapping[K, V]) -> dict[K, V]:
output: dict[K, V] = {}
for mapping in maps: output |= mapping
return output
def reversed_mapping(values: Mapping[K, K]) -> dict[K, K]:
if len(set(values.values())) != len(values):
raise ValueError('duplicate values would overwrite an inverted key')
return {value: key for key, value in values.items()}
def select_map(values: Iterable[T], select: Callable[[T], bool], transform: Callable[[T], R]) -> list[R]:
return [transform(value) for value in values if select(value)]
def flat(values: Iterable[Iterable[T]]) -> list[T]:
return [item for row in values for item in row]
def distinct(values: Iterable[K]) -> set[K]:
return {value for value in values}
def recurrence() -> Generator[int, None, None]:
left, right = 0, 1
while True:
yield left
left, right = right, left + right
def batches(values: Sequence[T], width: int) -> Iterator[Sequence[T]]:
if width <= 0: raise ValueError('batch width must be positive')
for offset in range(0, len(values), width): yield values[offset:offset + width]
def lines(path: Path) -> Iterator[str]:
with path.open(encoding='utf-8') as stream:
for line in stream: yield line.rstrip('\n')
@lru_cache(maxsize=96)
def cumulative_count(stop: int) -> int:
if stop < 0: raise ValueError('stop must not be negative')
return sum(range(stop + 1))
def _multiply(value: int, factor: int) -> int:
return value * factor
def multiplier(factor: int) -> Callable[[int], int]:
return partial(_multiply, factor=factor)
@contextmanager
def measured(label: str) -> Generator[None, None, None]:
begin = time.perf_counter()
try: yield
finally: logger.info('%s elapsed %.4fs', label, time.perf_counter() - begin)
@contextmanager
def ignore_selected(*exceptions: type[Exception]) -> Generator[None, None, None]:
try: yield
except exceptions: return
def split_head(values: Sequence[T]) -> tuple[T, list[T]]:
head, *tail = values
return head, tail
def endpoints(values: Sequence[T]) -> tuple[T, T]:
if not values: raise ValueError('at least one element required')
return values[0], values[-1]
def exchange(left: T, right: T) -> tuple[T, T]:
return right, left
def traced(function: Callable[P, R]) -> Callable[P, R]:
@wraps(function)
def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
logger.debug('Calling %s', function.__qualname__)
return function(*args, **kwargs)
return wrapped
class PreparedLabels:
def __init__(self, labels: Sequence[str]) -> None: self.labels = tuple(labels)
@cached_property
def normalized(self) -> tuple[str, ...]:
return tuple(value.strip().casefold() for value in self.labels)
@dataclass
class Coordinate:
x: float
y: float
def distance(self) -> float: return (self.x * self.x + self.y * self.y) ** 0.5
@dataclass(frozen=True)
class FixedCoordinate:
x: float
y: float
@dataclass
class WorkshopOptions:
name: str
values: list[int] = field(default_factory=list)
_cache: dict[str, int] = field(default_factory=dict, repr=False)
MAX_ITEMS: ClassVar[int] = 240
class Phase(Enum):
QUEUED = auto()
ACTIVE = auto()
FINISHED = auto()
class Theme(StrEnum):
LIGHT = 'light'
DARK = 'dark'
SYSTEM = 'system'
class Urgency(IntEnum):
ROUTINE = 1
IMPORTANT = 2
IMMEDIATE = 3
# Eight distinct static interchange shapes. They do not validate a dictionary at runtime.
class AttendeeContract(TypedDict):
user_id: int
email: str
is_active: bool
nickname: NotRequired[str]
class PlaceContract(TypedDict):
street: str
city: str
country: str
postal_code: NotRequired[str]
class BookingContract(TypedDict):
name: str
email: str
address: PlaceContract
class EnvelopeContract(TypedDict):
status: str
data: dict[str, object]
meta: NotRequired[dict[str, int]]
error: NotRequired[str]
class PageContract(TypedDict):
items: list[dict[str, object]]
page: int
page_size: int
total_items: int
has_next: NotRequired[bool]
has_prev: NotRequired[bool]
class OptionContract(TypedDict, total=False):
host: str
port: int
debug: bool
timeout: float
retries: int
class ConnectionContract(TypedDict):
credential_reference: Required[str]
base_url: Required[str]
timeout: NotRequired[int]
max_retries: NotRequired[int]
class JobContract(TypedDict):
task_id: str
status: str
result: NotRequired[dict[str, object]]
error: NotRequired[str]
started_at: NotRequired[str]
completed_at: NotRequired[str]
class FieldProblem(ValueError):
def __init__(self, field: str, message: str) -> None:
self.field, self.message = field, message
super().__init__(f'{field}: {message}')
def normalize_contact(value: str) -> str:
if '@' not in value: raise FieldProblem('contact', 'address delimiter missing')
return value.strip().casefold()
def format_value(value: int | str | None) -> str:
return '(missing)' if value is None else str(value)
def upper_labels(values: Sequence[str]) -> list[str]:
return [value.upper() for value in values]
def map_integers(values: Iterable[int], operation: Callable[[int], int]) -> list[int]:
return [operation(value) for value in values]Iterators, collections, and function tools
| Family | Concrete forms retained | |---|---|
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 38.2 kB | 89c9da915909 |
| examples.json | 1.9 kB | 895fc47e1693 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.