{"slug":"python-4","title":"python","summary":"Python language conventions, modern idioms, and toolchain. Invoke whenever task involves any interaction with Python code — writing, reviewing, refactoring, debugging, or understanding Python projects.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-10T18:27:26.150253Z","repo":{"url":"https://github.com/xobotyi/cc-foundry","stars":23,"forks":2,"license":"MIT","updatedAt":"2026-11-10T17:16:40Z"},"bodyHtml":"<hr>\n<h2>name: python\ndescription: &gt;-\nPython language conventions, modern idioms, and toolchain. Invoke whenever task involves any\ninteraction with Python code — writing, reviewing, refactoring, debugging, or understanding\nPython projects.</h2>\n<h1>Python</h1>\n<p><strong>Readability counts. Explicit is better than implicit. If your code needs a comment to explain its control flow,\nrestructure it.</strong></p>\n<p>Python 3.14+ is the baseline. Use modern syntax unconditionally — no backward compatibility with older Python versions\nunless the project explicitly requires it.</p>\n<h2>References</h2>\n<ul>\n<li><strong>[<code>${CLAUDE_SKILL_DIR}/references/typing.md</code>]</strong> — Type annotation patterns, generics, overloads, TypeVar, variance:\nfull annotation examples, generic class patterns, Protocol implementation, TypeVar usage</li>\n<li><strong>[<code>${CLAUDE_SKILL_DIR}/references/packaging.md</code>]</strong> — Project layout, pyproject.toml, uv, dependency management:\npyproject.toml templates, uv workflows, src layout, dependency groups, build backends</li>\n<li><strong>[<code>${CLAUDE_SKILL_DIR}/references/modules.md</code>]</strong> — Module system, imports, namespace packages, <code>__init__.py</code>: import\nresolution order, circular import fixes, lazy imports, namespace packages</li>\n<li><strong>[<code>${CLAUDE_SKILL_DIR}/references/concurrency.md</code>]</strong> — asyncio, TaskGroup, cancellation, timeouts, threading interop:\nTaskGroup error handling, timeout scopes, cancellation semantics, to_thread, eager task factory</li>\n</ul>\n<h2>Naming</h2>\n<ul>\n<li><strong>Variables, functions, methods</strong> — snake_case: <code>user_name</code>, <code>fetch_data</code></li>\n<li><strong>Classes, type aliases</strong> — PascalCase: <code>UserService</code>, <code>HttpClient</code></li>\n<li><strong>Constants</strong> — UPPER_SNAKE_CASE: <code>MAX_RETRIES</code>, <code>API_BASE_URL</code></li>\n<li><strong>Modules, packages</strong> — snake_case, short: <code>user_store</code>, <code>auth</code></li>\n<li><strong>Private attributes/methods</strong> — <code>_</code> prefix: <code>_internal_cache</code>, <code>_validate()</code></li>\n<li><strong>Name-mangled attributes</strong> — <code>__</code> prefix: <code>__secret</code> (rarely needed)</li>\n<li><strong>Type variables</strong> — PascalCase, short: <code>T</code>, <code>KT</code>, <code>VT</code>, <code>ResponseT</code></li>\n<li><strong>Protocols</strong> — PascalCase, <code>-able</code>/<code>-ible</code> suffix: <code>Renderable</code>, <code>Serializable</code></li>\n<li><strong>Descriptive names.</strong> <code>user_count</code> not <code>n</code>. Short names (<code>i</code>, <code>x</code>) only in tiny scopes (comprehensions, simple\nlambdas).</li>\n<li><strong>No redundant context.</strong> <code>car.make</code> not <code>car.car_make</code>.</li>\n<li><strong>Boolean names:</strong> <code>is_</code>/<code>has_</code>/<code>can_</code>/<code>should_</code> prefix: <code>is_valid</code>, <code>has_access</code>.</li>\n<li><strong>Dunder methods are reserved for the data model.</strong> Never invent custom dunder names.</li>\n<li><strong>Avoid single-character names</strong> outside loop indices, comprehension variables, and well-established conventions (<code>f</code>\nfor file, <code>e</code> for exception, <code>k</code>/<code>v</code> for key/value).</li>\n</ul>\n<h2>Type Annotations</h2>\n<p>Python 3.14+ uses modern annotation syntax natively. No <code>from __future__ import annotations</code> needed — all annotations\nare evaluated lazily by default.</p>\n<h3>Core Rules</h3>\n<ul>\n<li><strong>Annotate all public API boundaries</strong> — function signatures, class attributes, module-level variables. Internal code\noften needs fewer annotations; types flow from context.</li>\n<li><strong>Use built-in generics:</strong> <code>list[str]</code>, <code>dict[str, int]</code>, <code>tuple[int, ...]</code>, <code>set[float]</code>. Never import <code>List</code>,\n<code>Dict</code>, <code>Tuple</code>, <code>Set</code> from <code>typing</code>.</li>\n<li><strong>Union with <code>|</code>:</strong> <code>str | None</code>, <code>int | float</code>. Never <code>Optional[X]</code> or <code>Union[X, Y]</code>.</li>\n<li><strong><code>type</code> statement for aliases:</strong> <code>type Vector = list[float]</code>. Not <code>TypeAlias</code> annotation.</li>\n<li><strong><code>None</code> return:</strong> annotate <code>-&gt; None</code> on functions that return nothing. Omit return type only on <code>__init__</code>.</li>\n<li><strong>Avoid <code>Any</code></strong> — it disables type checking. Use <code>object</code> when you mean \"any type but still type-safe.\" Use <code>Any</code> only\nat true interop boundaries with untyped code.</li>\n</ul>\n<h3>Generics</h3>\n<ul>\n<li><strong><code>type</code> parameter syntax (3.12+):</strong> <code>class Stack[T]:</code> and <code>def first[T](items: list[T]) -&gt; T:</code> instead of <code>TypeVar</code>\ndeclarations.</li>\n<li><strong>Constrained type parameters:</strong> <code>def process[T: (str, bytes)](data: T) -&gt; T:</code> for a finite set of allowed types.</li>\n<li><strong>Bounded type parameters:</strong> <code>def sort[T: Comparable](items: list[T]) -&gt; list[T]:</code> for upper-bound constraints.</li>\n<li><strong>Variance is inferred</strong> from usage in 3.12+ generics. No manual <code>covariant</code>/<code>contravariant</code> flags needed.</li>\n</ul>\n<h3>Protocols (Structural Typing)</h3>\n<ul>\n<li><strong>Prefer protocols over ABCs</strong> when you don't control the implementing types or when structural compatibility is\nsufficient.</li>\n<li><strong><code>@runtime_checkable</code></strong> only when you need <code>isinstance()</code> checks — it adds overhead and only validates method\npresence, not signatures.</li>\n<li><strong>Keep protocols small</strong> — one to three methods. A protocol with many methods is a sign you need an ABC or a concrete\nbase class.</li>\n</ul>\n<pre><code>from typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass Renderable(Protocol):\n    def render(self) -&gt; str: ...\n</code></pre>\n<h3>Callable Types</h3>\n<ul>\n<li><strong><code>collections.abc.Callable</code></strong> for callable annotations: <code>Callable[[int, str], bool]</code>.</li>\n<li><strong><code>ParamSpec</code></strong> for decorators that preserve signatures:\n<code>def decorator[**P, R](fn: Callable[P, R]) -&gt; Callable[P, R]:</code>.</li>\n<li><strong>Use <code>Protocol</code></strong> for complex callable signatures with keyword arguments or overloads.</li>\n</ul>\n<h3>TypeGuard and TypeIs</h3>\n<ul>\n<li><strong><code>TypeIs</code></strong> (3.13+) for narrowing that refines the input type:\n<code>def is_str_list(val: list[object]) -&gt; TypeIs[list[str]]:</code>.</li>\n<li><strong><code>TypeGuard</code></strong> for narrowing where the output type is unrelated to input:\n<code>def is_valid_config(data: object) -&gt; TypeGuard[Config]:</code>.</li>\n</ul>\n<p>See <code>${CLAUDE_SKILL_DIR}/references/typing.md</code> for full annotation patterns, generics, overloads, and variance.</p>\n<h2>Data Classes and Structured Data</h2>\n<h3>dataclasses</h3>\n<ul>\n<li><strong>Use <code>@dataclass</code> for data containers</strong> — classes that primarily hold data with minimal behavior.</li>\n<li><strong><code>frozen=True</code></strong> for immutable data: <code>@dataclass(frozen=True)</code>. Default to frozen unless mutation is required.</li>\n<li><strong><code>slots=True</code></strong> for memory efficiency and attribute safety: <code>@dataclass(slots=True, frozen=True)</code>.</li>\n<li><strong><code>kw_only=True</code></strong> when constructors have more than 3 fields — prevents positional argument ordering bugs.</li>\n<li><strong><code>field(default_factory=list)</code></strong> for mutable defaults. Never use mutable default arguments.</li>\n<li><strong>Post-init processing:</strong> <code>__post_init__</code> for derived fields and validation.</li>\n</ul>\n<pre><code>@dataclass(frozen=True, slots=True, kw_only=True)\nclass User:\n    name: str\n    email: str\n    roles: list[str] = field(default_factory=list)\n</code></pre>\n<h3>When NOT to Use dataclasses</h3>\n<ul>\n<li><strong>Simple value containers</strong> with 1-2 fields: use <code>NamedTuple</code> or plain tuples.</li>\n<li><strong>Config/settings with validation:</strong> use Pydantic or attrs with validators.</li>\n<li><strong>Persistence/ORM models:</strong> use the ORM's model base class.</li>\n</ul>\n<h3>NamedTuple</h3>\n<ul>\n<li><strong>Use <code>class</code> syntax</strong> over functional form: <code>class Point(NamedTuple): x: float; y: float</code>.</li>\n<li>NamedTuples are immutable and iterable — useful as dict keys and in destructuring.</li>\n</ul>\n<h2>Enums</h2>\n<ul>\n<li><strong>Use <code>enum.Enum</code></strong> for categorical constants. Never use bare strings or ints as pseudo-enums.</li>\n<li><strong><code>enum.StrEnum</code></strong> when the enum must interoperate with string APIs (JSON, config keys).</li>\n<li><strong><code>enum.IntEnum</code></strong> only when integer interop is mandatory (legacy protocols). Prefer <code>Enum</code> otherwise.</li>\n<li><strong><code>@enum.unique</code></strong> to prevent duplicate values.</li>\n<li><strong>Access by value:</strong> <code>Color(1)</code>. Access by name: <code>Color[\"RED\"]</code>. Iteration: <code>for c in Color:</code>.</li>\n<li><strong>Never subclass enums with members.</strong> Enums with members are final.</li>\n</ul>\n<pre><code>from enum import StrEnum, unique\n\n@unique\nclass Status(StrEnum):\n    ACTIVE = \"active\"\n    INACTIVE = \"inactive\"\n    SUSPENDED = \"suspended\"\n</code></pre>\n<h2>Pattern Matching</h2>\n<p><code>match</code>/<code>case</code> (3.10+) is the preferred dispatch mechanism for structural patterns.</p>\n<ul>\n<li><strong>Use match for structural dispatch</strong> — matching on type, shape, or destructured values. Don't use match as a\nsubstitute for simple <code>if</code>/<code>elif</code> chains on a single value.</li>\n<li><strong>Always include a wildcard <code>case _:</code> arm</strong> unless the match is provably exhaustive.</li>\n<li><strong>Guard clauses</strong> with <code>if</code>: <code>case Point(x, y) if x &gt; 0:</code>.</li>\n<li><strong>Use <code>|</code> for alternatives:</strong> <code>case \"quit\" | \"exit\" | \"q\":</code>.</li>\n<li><strong>Capture with walrus:</strong> <code>case {\"error\": str() as msg}:</code> captures while matching type.</li>\n<li><strong>Class patterns</strong> require <code>__match_args__</code> or keyword patterns: <code>case Point(x=0, y=y):</code>.</li>\n</ul>\n<pre><code>match command:\n    case {\"action\": \"move\", \"direction\": str() as direction}:\n        move(direction)\n    case {\"action\": \"attack\", \"target\": str() as target}:\n        attack(target)\n    case _:\n        raise ValueError(f\"Unknown command: {command}\")\n</code></pre>\n<h2>Functions</h2>\n<ul>\n<li><strong>Early return.</strong> Guard clauses first, happy path flat. Reduce nesting.</li>\n<li><strong>One function, one job.</strong> If the name contains \"and\", split it.</li>\n<li><strong>Type-annotate all parameters and return types</strong> on public functions.</li>\n<li><strong>Default arguments:</strong> immutable values only. Use <code>None</code> + conditional for mutable defaults:\n<code>def f(items: list[int] | None = None):</code> then <code>items = items or []</code> in body. Never <code>def f(items: list[int] = []):</code>.</li>\n<li><strong><code>*</code> to force keyword-only arguments</strong> after positional params: <code>def connect(host: str, *, port: int = 443):</code>.</li>\n<li><strong><code>/</code> to force positional-only</strong> for parameters that callers shouldn't name: <code>def sqrt(x: float, /) -&gt; float:</code>.</li>\n<li><strong>Prefer returning values</strong> over mutating arguments. Functions should be referentially transparent when possible.</li>\n<li><strong><code>None</code> means absent, not error.</strong> Return <code>T | None</code> for optional results. Raise exceptions for errors.</li>\n</ul>\n<h2>Decorators</h2>\n<ul>\n<li><p><strong>Preserve signatures</strong> with <code>functools.wraps</code>:</p>\n<pre><code>def retry[**P, R](fn: Callable[P, R]) -&gt; Callable[P, R]:\n    @functools.wraps(fn)\n    def wrapper(*args: P.args, **kwargs: P.kwargs) -&gt; R:\n        ...\n    return wrapper\n</code></pre>\n</li>\n<li><p><strong>Decorator order matters.</strong> Decorators apply bottom-up. <code>@staticmethod</code> and <code>@classmethod</code> must be outermost (topmost\nin source).</p>\n</li>\n<li><p><strong>Parametric decorators</strong> return a decorator: <code>@retry(attempts=3)</code> means <code>retry</code> returns the actual decorator\nfunction.</p>\n</li>\n<li><p><strong>Don't over-abstract with decorators.</strong> If the decorator hides important control flow (error handling, transaction\nmanagement), make it explicit instead.</p>\n</li>\n</ul>\n<h2>Context Managers</h2>\n<ul>\n<li><p><strong><code>contextlib.contextmanager</code></strong> for simple resource management:</p>\n<pre><code>@contextmanager\ndef managed_connection(url: str) -&gt; Iterator[Connection]:\n    conn = Connection(url)\n    try:\n        yield conn\n    finally:\n        conn.close()\n</code></pre>\n</li>\n<li><p><strong>Class-based context managers</strong> when state management is complex — implement <code>__enter__</code> and <code>__exit__</code>.</p>\n</li>\n<li><p><strong><code>contextlib.suppress(ExceptionType)</code></strong> instead of empty <code>except: pass</code>.</p>\n</li>\n<li><p><strong><code>contextlib.closing(thing)</code></strong> for objects with <code>.close()</code> but no <code>__exit__</code>.</p>\n</li>\n<li><p><strong><code>contextlib.asynccontextmanager</code></strong> for async resource management.</p>\n</li>\n<li><p><strong>Always use <code>with</code></strong> for files, locks, database connections, and any resource that needs deterministic cleanup.</p>\n</li>\n</ul>\n<h2>Generators and Iterators</h2>\n<ul>\n<li><strong>Generators for lazy sequences.</strong> Use <code>yield</code> to produce values on demand instead of building full lists in memory.</li>\n<li><strong>Generator expressions</strong> over list comprehensions when the result is iterated only once:\n<code>sum(x * x for x in range(1000))</code>.</li>\n<li><strong><code>yield from</code></strong> to delegate to sub-generators — preserves <code>.send()</code>, <code>.throw()</code>, <code>.close()</code> protocol.</li>\n<li><strong><code>itertools</code></strong> for composition: <code>chain</code>, <code>islice</code>, <code>groupby</code>, <code>batched</code> (3.12+), <code>pairwise</code> (3.10+).</li>\n<li><strong>Annotate generators:</strong> <code>def gen() -&gt; Iterator[int]:</code> for simple generators,\n<code>Generator[YieldType, SendType, ReturnType]</code> when using <code>.send()</code>.</li>\n<li><strong>Never exhaust a generator twice.</strong> Generators are single-pass. If you need multiple passes, materialize to a list or\nuse <code>itertools.tee</code>.</li>\n</ul>\n<h2>Comprehensions</h2>\n<ul>\n<li><strong>List/dict/set comprehensions</strong> for simple transforms: <code>[x.name for x in users if x.active]</code>.</li>\n<li><strong>One level of nesting maximum.</strong> Two nested <code>for</code> clauses are the absolute limit. Beyond that, extract to a function.</li>\n<li><strong>Don't use comprehensions for side effects.</strong> <code>[print(x) for x in items]</code> is wrong — use a <code>for</code> loop.</li>\n<li><strong>Walrus operator in comprehensions</strong> for compute-once-filter-and-use:\n<code>[y for x in data if (y := transform(x)) is not None]</code>.</li>\n<li><strong>Dict comprehensions</strong> for key transformations: <code>{k.lower(): v for k, v in headers.items()}</code>.</li>\n</ul>\n<h2>Exception Handling</h2>\n<ul>\n<li><p><strong>Be specific.</strong> Catch the narrowest exception type: <code>except ValueError:</code> not <code>except Exception:</code>.</p>\n</li>\n<li><p><strong>Never bare <code>except:</code>.</strong> It catches <code>SystemExit</code>, <code>KeyboardInterrupt</code>, and <code>GeneratorExit</code>. At minimum use\n<code>except Exception:</code>.</p>\n</li>\n<li><p><strong><code>except* ExceptionGroup</code></strong> (3.11+) for handling multiple concurrent exceptions from <code>TaskGroup</code> and similar.</p>\n</li>\n<li><p><strong>Wrap with context.</strong> <code>raise AppError(\"context\") from err</code> chains the original cause.</p>\n</li>\n<li><p><strong>Don't use exceptions for flow control.</strong> <code>if key in dict:</code> not <code>try: dict[key] except KeyError:</code> (unless the miss is\nrare and lookup is expensive).</p>\n</li>\n<li><p><strong>Custom exceptions</strong> inherit from a project-specific base that extends <code>Exception</code>:</p>\n<pre><code>class AppError(Exception): ...\nclass NotFoundError(AppError): ...\nclass ValidationError(AppError): ...\n</code></pre>\n</li>\n<li><p><strong>Error strings:</strong> lowercase, no trailing punctuation. They compose in chains: <code>\"parse config: invalid format\"</code>.</p>\n</li>\n<li><p><strong><code>else</code> clause</strong> runs only when no exception was raised — use for code that should execute on success but isn't part\nof the <code>try</code> body.</p>\n</li>\n<li><p><strong><code>finally</code></strong> for unconditional cleanup — prefer context managers when possible.</p>\n</li>\n<li><p><strong>Exception groups (3.11+):</strong> use <code>ExceptionGroup</code> to bundle multiple errors. Handle with <code>except*</code> which matches by\ntype and re-raises unhandled exceptions.</p>\n</li>\n<li><p><strong>Add notes with <code>.add_note()</code></strong> (3.11+) to attach context without creating new exception types.</p>\n</li>\n</ul>\n<h2>Strings</h2>\n<ul>\n<li><strong>f-strings</strong> for interpolation. Never <code>%</code> formatting or <code>.format()</code> in new code.</li>\n<li><strong>f-string expressions must be simple.</strong> No function calls with multiple arguments, no nested f-strings, no complex\nexpressions. Extract to a variable first.</li>\n<li><strong><code>str.removeprefix()</code> / <code>str.removesuffix()</code></strong> (3.9+) over slicing.</li>\n<li><strong>Triple-quoted strings</strong> for multiline. Use <code>textwrap.dedent</code> when indentation matters.</li>\n<li><strong><code>\"\".join(parts)</code></strong> for building strings in loops — never <code>+=</code> in a loop.</li>\n<li><strong>Raw strings <code>r\"...\"</code></strong> for regex patterns and Windows paths.</li>\n</ul>\n<h2>Pathlib</h2>\n<ul>\n<li><strong><code>pathlib.Path</code></strong> for all filesystem operations. Never <code>os.path</code> in new code.</li>\n<li><strong><code>/</code> operator</strong> for path joining: <code>base / \"subdir\" / \"file.txt\"</code>.</li>\n<li><strong>Common operations:</strong> <code>path.exists()</code>, <code>path.is_file()</code>, <code>path.is_dir()</code>, <code>path.read_text()</code>, <code>path.write_text()</code>,\n<code>path.mkdir(parents=True, exist_ok=True)</code>, <code>path.iterdir()</code>, <code>path.glob(\"*.py\")</code>, <code>path.rglob(\"**/*.py\")</code>.</li>\n<li><strong><code>path.resolve()</code></strong> for absolute paths. <code>path.relative_to(base)</code> for relative paths.</li>\n<li><strong>Accept <code>str | Path</code></strong> in public APIs, convert to <code>Path</code> internally.</li>\n</ul>\n<h2>Imports</h2>\n<ul>\n<li><strong>Absolute imports</strong> by default: <code>from mypackage.utils import helper</code>.</li>\n<li><strong>Relative imports</strong> only within packages for tightly coupled modules: <code>from .models import User</code>.</li>\n<li><strong>Import grouping</strong> (separated by blank lines):\n<ol>\n<li>Standard library (<code>import os</code>, <code>from pathlib import Path</code>)</li>\n<li>Third-party (<code>import httpx</code>, <code>from pydantic import BaseModel</code>)</li>\n<li>Local (<code>from myapp.models import User</code>)</li>\n</ol>\n</li>\n<li><strong>Import specific names:</strong> <code>from collections import defaultdict</code> not <code>import collections</code> (unless you use many names\nfrom the module).</li>\n<li><strong>Never <code>from module import *</code></strong> — pollutes namespace, breaks type checkers, hides dependencies.</li>\n<li><strong><code>if TYPE_CHECKING:</code> block</strong> for imports used only in annotations — avoids circular imports and runtime overhead. In\n3.14+ with lazy annotations, this is less necessary but still useful for avoiding circular import side effects.</li>\n<li><strong>Lazy imports</strong> in function bodies when a top-level import would create a circular dependency or when the import is\nexpensive and rarely needed.</li>\n</ul>\n<h2>Classes</h2>\n<h3>Slots</h3>\n<ul>\n<li><strong>Always use <code>__slots__</code></strong> on classes that will have many instances — prevents <code>__dict__</code> creation, saves memory,\ncatches typos in attribute names.</li>\n<li><strong><code>@dataclass(slots=True)</code></strong> adds slots automatically.</li>\n<li><strong>Slots and inheritance:</strong> every class in the hierarchy must declare <code>__slots__</code>. Missing slots on a parent\nreintroduces <code>__dict__</code>.</li>\n</ul>\n<h3>Dunder Methods</h3>\n<ul>\n<li><strong><code>__repr__</code></strong> on every class — must be unambiguous: <code>def __repr__(self) -&gt; str: return f\"User(name={self.name!r})\"</code>.</li>\n<li><strong><code>__str__</code></strong> only when a human-readable form differs from repr.</li>\n<li><strong><code>__eq__</code> and <code>__hash__</code></strong> — if you define <code>__eq__</code>, define <code>__hash__</code> too (or set <code>__hash__ = None</code> to make\nunhashable). Mutable objects should not be hashable.</li>\n<li><strong><code>__bool__</code></strong> — define when truthiness of instances has meaningful semantics.</li>\n<li><strong><code>__enter__</code>/<code>__exit__</code></strong> for context manager protocol.</li>\n<li><strong><code>__init_subclass__</code></strong> for class registration patterns without metaclasses.</li>\n<li><strong><code>__class_getitem__</code></strong> to make classes subscriptable for generic type hints.</li>\n</ul>\n<h3>Inheritance</h3>\n<ul>\n<li><strong>Composition over inheritance.</strong> Use inheritance only for true \"is-a\" relationships.</li>\n<li><strong>ABCs for interfaces</strong> when you control both sides and need enforced implementation:\n<code>from abc import ABC, abstractmethod</code>.</li>\n<li><strong>Protocols for duck typing</strong> when you don't control implementations.</li>\n<li><strong><code>super()</code></strong> — always use <code>super()</code> (no arguments in 3.x). Never hardcode parent class names.</li>\n<li><strong>MRO awareness.</strong> Understand method resolution order in diamond inheritance. When in doubt, avoid multiple\ninheritance.</li>\n</ul>\n<h3>Class Methods and Static Methods</h3>\n<ul>\n<li><strong><code>@classmethod</code></strong> for alternative constructors: <code>User.from_dict(data)</code>.</li>\n<li><strong><code>@staticmethod</code></strong> for utility functions that don't need class or instance state — but prefer module-level functions\nunless the function is logically part of the class's API.</li>\n</ul>\n<h2>Packaging and Toolchain</h2>\n<h3>pyproject.toml</h3>\n<ul>\n<li><strong><code>pyproject.toml</code> is the single source of truth</strong> for project metadata, dependencies, tool configuration. Never\n<code>setup.py</code> or <code>setup.cfg</code> in new projects.</li>\n<li><strong>Build backend:</strong> use <code>hatchling</code>, <code>flit-core</code>, or <code>setuptools</code> with <code>[build-system]</code> table.</li>\n<li><strong>Dependency specification:</strong> pin with <code>&gt;=</code> lower bound, avoid upper bounds unless genuinely incompatible:\n<code>httpx&gt;=0.27</code>.</li>\n</ul>\n<h3>uv</h3>\n<ul>\n<li><strong><code>uv</code></strong> is the preferred Python package manager and environment tool.</li>\n<li><strong><code>uv sync</code></strong> to install dependencies from lock file.</li>\n<li><strong><code>uv add &lt;package&gt;</code></strong> to add dependencies.</li>\n<li><strong><code>uv run &lt;command&gt;</code></strong> to run commands in the project environment.</li>\n<li><strong><code>uv lock</code></strong> to generate/update the lock file.</li>\n<li><strong><code>uv venv</code></strong> to create virtual environments.</li>\n<li><strong><code>uv python install 3.14</code></strong> to install Python versions.</li>\n</ul>\n<h3>Project Layout</h3>\n<pre><code>my-project/\n├── pyproject.toml\n├── uv.lock\n├── src/\n│   └── my_package/\n│       ├── __init__.py\n│       └── ...\n└── tests/\n    ├── conftest.py\n    └── ...\n</code></pre>\n<ul>\n<li><strong>src layout</strong> — package code lives under <code>src/</code>. Prevents accidental imports from the project root during testing.</li>\n<li><strong><code>__init__.py</code></strong> — keep minimal. Define <code>__all__</code> for public API. Don't put substantial logic in init files.</li>\n</ul>\n<h3>Linting and Formatting</h3>\n<ul>\n<li><strong><code>ruff</code></strong> for both linting and formatting. Single tool, fast.</li>\n<li><strong><code>ruff check</code></strong> to lint. <strong><code>ruff format</code></strong> to format.</li>\n<li><strong>Configure in <code>pyproject.toml</code></strong> under <code>[tool.ruff]</code>.</li>\n</ul>\n<p>See <code>${CLAUDE_SKILL_DIR}/references/packaging.md</code> for pyproject.toml templates, uv workflows, and dependency management\npatterns.</p>\n<h2>Concurrency</h2>\n<h3>asyncio</h3>\n<ul>\n<li><strong><code>async</code>/<code>await</code></strong> for I/O-bound concurrency.</li>\n<li><strong><code>asyncio.TaskGroup</code></strong> (3.11+) for structured concurrency — replaces <code>asyncio.gather()</code> with better error handling.</li>\n<li><strong>Never use <code>asyncio.gather()</code></strong> in new code — it has inconsistent error semantics. Use <code>TaskGroup</code> instead.</li>\n<li><strong><code>asyncio.run()</code></strong> as the single entry point. Never <code>loop.run_until_complete()</code>.</li>\n<li><strong>Cancel via <code>asyncio.CancelledError</code></strong> — always clean up resources in <code>finally</code> blocks.</li>\n</ul>\n<h3>threading</h3>\n<ul>\n<li><strong><code>concurrent.futures.ThreadPoolExecutor</code></strong> for CPU-light I/O-bound parallel work.</li>\n<li><strong><code>threading.Lock</code></strong> for shared mutable state. Always use <code>with lock:</code> context manager.</li>\n<li><strong>GIL note:</strong> in CPython, threads don't achieve true parallelism for CPU-bound work. Use <code>multiprocessing</code> or\n<code>ProcessPoolExecutor</code> for CPU-bound tasks.</li>\n<li><strong>Free-threaded Python (3.13+):</strong> when running with <code>--disable-gil</code>, standard thread-safety practices become critical.\nGuard all shared mutable state with locks.</li>\n</ul>\n<h3>General Rules</h3>\n<ul>\n<li><strong>Structured concurrency preferred.</strong> <code>TaskGroup</code> and context managers over bare <code>create_task()</code>.</li>\n<li><strong>Never fire-and-forget</strong> tasks or threads — always track completion.</li>\n<li><strong>Cancellation must be cooperative.</strong> Check for cancellation and clean up.</li>\n</ul>\n<h2>Logging</h2>\n<ul>\n<li><strong><code>logging</code> module</strong> over <code>print()</code> for anything beyond quick debugging.</li>\n<li><strong><code>logger = logging.getLogger(__name__)</code></strong> at module level.</li>\n<li><strong>Lazy formatting:</strong> <code>logger.info(\"User %s logged in\", user_id)</code> not <code>logger.info(f\"User {user_id} logged in\")</code> —\nf-string evaluates even when level is disabled.</li>\n<li><strong>Use appropriate levels:</strong> <code>DEBUG</code> for diagnostics, <code>INFO</code> for operational events, <code>WARNING</code> for degraded but\nworking, <code>ERROR</code> for failures, <code>CRITICAL</code> for system-down.</li>\n</ul>\n<h2>Application</h2>\n<p>When <strong>writing</strong> Python code: apply all conventions silently — don't narrate each rule. If an existing codebase\ncontradicts a convention, follow the codebase and flag the divergence once.</p>\n<p>When <strong>reviewing</strong> Python code: cite the specific violation and show the fix inline. Don't lecture — state what's wrong\nand how to fix it.</p>\n<pre><code>Bad:  \"According to Python best practices, you should use type unions\n       with the pipe operator instead of Optional...\"\nGood: \"Optional[str] -&gt; str | None\"\n</code></pre>\n<h2>Code Navigation — LSP Required</h2>\n<p>A <code>pyright-langserver</code> LSP server is configured for <code>.py</code> and <code>.pyi</code> files. <strong>Always use LSP tools for code navigation\ninstead of Grep or Glob.</strong> LSP understands Python's module system, type inference, scope rules, and package boundaries —\ntext search does not.</p>\n<h3>Tool Routing</h3>\n<ul>\n<li><strong><code>goToDefinition</code></strong> — find where a function/class/variable is defined: resolves imports, re-exports, aliases</li>\n<li><strong><code>findReferences</code></strong> — find all usages of a symbol: scope-aware, no false positives from string matches</li>\n<li><strong><code>hover</code></strong> — get type signature, docs, or return types: instant type info without reading source files</li>\n<li><strong><code>documentSymbol</code></strong> — list all symbols in a file: structured output vs grepping for <code>def</code>/<code>class</code></li>\n<li><strong><code>workspaceSymbol</code></strong> — find a symbol by name across the project: searches all packages, respects <code>__all__</code></li>\n<li><strong><code>goToImplementation</code></strong> — find implementations of a Protocol or ABC: knows the type system and structural subtyping</li>\n<li><strong><code>incomingCalls</code></strong> — find what calls a function: precise call graph across module boundaries</li>\n<li><strong><code>outgoingCalls</code></strong> — find what a function calls: structured dependency map</li>\n</ul>\n<p><strong>Grep/Glob remain appropriate for:</strong> text in comments, string literals, log messages, TODO markers, config values, env\nvars, file name patterns, URLs, error message text — anything that isn't a Python identifier.</p>\n<p>When spawning subagents for Python codebase exploration, instruct them to use LSP tools. Subagents have access to the\nsame LSP server.</p>\n<h2>Toolchain</h2>\n<ul>\n<li><strong><code>ruff</code></strong>: single entry point for linting and formatting. Must pass before committing.\n<ul>\n<li><code>ruff check</code> — lint. <code>ruff check --fix</code> — auto-fix.</li>\n<li><code>ruff format</code> — format.</li>\n</ul>\n</li>\n<li><strong><code>uv</code></strong>: package management, virtual environments, Python version management.</li>\n<li><strong><code>mypy</code> or <code>pyright</code></strong>: static type checking. Configure in <code>pyproject.toml</code>.</li>\n</ul>\n<h2>Integration</h2>\n<p>The <strong>coding</strong> skill governs workflow (discovery, planning, verification); this skill governs Python implementation\nchoices. The <strong>pytest</strong> skill governs testing conventions — both are active simultaneously when writing Python tests.</p>\n<p><strong>Readability counts. If you read a function twice to understand it, rewrite it once to make it clear.</strong></p>\n","files":[{"path":".dev/reference-inventory.json","sizeBytes":1298,"isText":true},{"path":"references/concurrency.md","sizeBytes":7904,"isText":true},{"path":"references/modules.md","sizeBytes":6907,"isText":true},{"path":"references/packaging.md","sizeBytes":9205,"isText":true},{"path":"references/typing.md","sizeBytes":11783,"isText":true},{"path":"SKILL.md","sizeBytes":23559,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-10T18:28:24.857491Z","sha256":"41CB8512F61E235DE4A65C59DA36D3E5546E209EAA8ED52296B18AE954989911","sizeBytes":24722},"review":null,"source":{"repositoryUrl":"https://github.com/xobotyi/cc-foundry","path":"plugins/python/skills/python","license":"MIT","commit":"278c16c0c371ac3ef36b12512ca558c7513ef13e","subtreeSha":"08A2D4EE8613EE35228E1505210F94359DB50140515957033507B4CBA2A73D9F","lastSyncedAt":"2026-11-10T18:27:15.736835Z"},"reviewedAt":"2026-11-10T18:30:14.068599Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/xobotyi/cc-foundry/tree/master/plugins/python/skills/python"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install xobotyi-cc-foundry@llmmart"},{"target":"git","command":"git clone https://github.com/xobotyi/cc-foundry.git"}]}