agentleFS
kalaverinkalaverin/skills/python-lang/SKILL.md

python-lang

Skill1 starsChanged 3 days agoBSD-3-ClauseView on GitHub

MANDATORY skill for Python code. Use when writing, editing, refactoring, or reviewing Python files, modules, packages, classes, functions, type annotations, imports, exceptions, comprehensions, decorators, or docstrings. Enforces Google Python Style Guide and a mandatory, unconditional Ruff format+check pipeline scoped strictly to the agent's own changes.

The file

Show its rules and text

We split this skill into the rules it gives an agent

30 rules. About 0 are common, 14 are distinctive, and 16 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈14

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 16

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Deviation Justification: If you deviate from any MUST directive, you MUST explicitly justify the deviation in your output.

    line 24
  2. Very specific:

    Run the subject map (Command 1) over references/ and shortlist candidate files semantically — the request plus inferred session work.

    line 45
  3. Very specific:

    Read the full frontmatter of shortlisted files — 03_personal_rules.md is always shortlisted — and match every card's what / use_when / …

    line 46
  4. Distinctive:

    If a violation exists in unmodified code, ignore it completely.

    line 68
  5. Distinctive:

    If the linter suggests moving or refactoring that would affect unmodified code, skip the suggestion.

    line 69
  6. Very specific:

    Run every pipeline command with an explicit file list (<changed_files>) — NEVER against the whole project, a whole directory, or files you …

    line 70
  7. Very specific:

    Inspect every hunk: After formatting, run git diff <file> (or diff against the backup) and review each hunk individually.

    line 76
  8. Distinctive:

    Justify unavoidable bleed: If a formatter-mandated change physically cannot be limited to your own lines (for example, the formatter …

    line 79
  9. Distinctive:

    Run the formatter targeting ONLY the files you created or modified, then immediately perform the Restoring Foreign Code After Formatting …

    line 90
  10. Very specific:

    Run the following command targeting ONLY the files you modified — the --fix flag is MANDATORY on this first lint pass (see the HARD rules …

    line 97
  11. Very specific:

    Read every REMAINING suggestion carefully (these are the ones --fix could not repair).

    line 101
  12. Distinctive:

    After applying fixes, confirm no auto-fixable violations remain — the emitted diff MUST be empty (any non-empty hunk is a fix you still owe …

    line 104
  13. Distinctive:

    If you are uncertain about any rule code generated by the linter, use:

    line 111
  14. Very specific:

    Route: Run the §2 routing funnel over the references/ corpus (subject map → frontmatter cards → bounded extraction of the selected py-* …

    line 125
  15. Distinctive:

    Code Generation: Write the code strictly adhering to the extracted rules, the reuse manifests, AND local file consistency.

    line 126
  16. Very specific:

    Before implementing any new Python module, class, or function, the agent MUST check whether the project root contains a .sdk/ directory.

    line 134
  17. Very specific:

    If .sdk/ exists, discover all reuse manifests with: fd -L -t f EXPORT.md .sdk/

    line 137
  18. Distinctive:

    Read every returned file before writing code.

    line 139
  19. Distinctive:

    After copying a module, replace the source package prefix with the target project's package prefix and run the Mandatory Lint & Format …

    line 144
  20. Very specific:

    Prefer auto() for every member whose concrete value is not semantically significant.

    line 183
  21. Very specific:

    Do not use magic strings or numbers as sentinels (e.g., result = -1, name = "N/A", value = 999).

    line 195
  22. Distinctive:

    Use a dedicated enum member or a singleton sentinel object:

    line 196
  23. Very specific:

    If the value can be modeled as a dataclass or Pydantic model, use that instead of Literal.

    line 214
  24. Very specific:

    If starlette is available, use from starlette import status and status.HTTP_200_OK.

    line 219
  25. Very specific:

    Never use 200, 201, 400, 404, 500, etc.

    line 221
  26. Distinctive:

    Every argument MUST be passed explicitly by name or position.

    line 236
  27. Very specific:

    Run the §3 pipeline on every changed file.

    line 278
  28. Distinctive:

    Every Python file that produces any diagnostic, status, warning, or error output MUST define a module-level logger:

    line 287
  29. Distinctive:

    Never swallow exceptions, errors, or unusual conditions silently.

    line 293
  30. Very specific:

    Use logger.exception(...) inside except blocks to capture the traceback.

    line 294

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

SKILL: Strict Python Engineering & Compliance

You are an expert Python Engineer and a strict Code Reviewer. This document is a binding rule set, not a recommendation. Every directive in this guide MUST be followed unless it explicitly uses SHOULD or MAY. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when they appear in all capitals or in bold markup.

1. Compliance and Local Style

  • Default Rule: Unless a section, paragraph, or sentence explicitly uses SHOULD or MAY, every statement is to be treated as MUST. If a coding situation is covered by this guide, you MUST follow the guide. You MUST NOT apply external style preferences or general Python heuristics in place of the rules documented here.
  • Consistency: BE CONSISTENT. If you are editing code, ALWAYS look at the code around you and you MUST match its style. Local style is VERY IMPORTANT. If code you add looks drastically different from the existing code, it throws readers out of their rhythm. Consistency applies more heavily locally and on choices unspecified by the global style.
  • Deviation Justification: If you deviate from any MUST directive, you MUST explicitly justify the deviation in your output.
  • Skill Boundary: This skill covers Python language and style rules. For API resource design, HTTP/gRPC routes, and proto structure, consult the api-design skill.
  • RFC Verbs: For precise semantics of requirement-level verbs, consult the read-for-comments skill.

2. Mandatory Lookups (Lazy-Load Protocol)

This routing is mandatory. When the task touches Python language or style rules, you MUST route through the corpus frontmatter before reading any body. Do not guess, do not rely on training data, and do not skip routing because the topic seems familiar. You MUST NOT read the reference files in their entirety.

Corpus:

  • references/01_language_rules.md — Google language rules; 20 routable sections, anchors py-lr-*.
  • references/02_style_rules.md — Google style rules; 53 routable sections including the subsection-level chapters 2.8 / 2.10 / 2.16 / 2.19, anchors py-st-*.
  • references/03_personal_rules.md — project-specific rules that EXTEND and OVERRIDE the Google corpora on conflict, anchors py-pr-*. Its frontmatter is small: shortlist it on EVERY funnel pass so overrides are never missed.

Toolchain precedence (HARD): the corpus reproduces upstream Google text that references pylint and pytype. Those references are historical context only. The governing local toolchain is Ruff for lint/format (§3, mandatory) and mypy for type checking (03_personal_rules.md). Where a corpus section and this skill's §3 conflict, §3 wins; say so per §1 (Deviation Justification).

Skill addendum (lazyload): prompts/REFERENCE_STANDARD_ADDENDUM.md declares the two-tier anchor prefixes (py-lr-, py-st-, py-pr-), the tight marker_style, the Google-canon numbered-headings exemption, and the pseudo-heading legalization. Corpus frontmatter schema and card semantics defer to frontmatter-protocol/references/lazyload.md.

Routing Funnel (per frontmatter-protocol [ref: #lazy-load-routing]):

  1. Run the subject map (Command 1) over references/ and shortlist candidate files semantically — the request plus inferred session work; shortlist generously.
  2. Read the full frontmatter of shortlisted files — 03_personal_rules.md is always shortlisted — and match every card's what / use_when / avoid_when semantically (OR semantics); mark each matching card's anchor.
  3. Deduplicate anchors, then extract each selected section with the canonical bounded extraction — never a blind rg -A N window.
  4. Apply the extracted rules strictly.

3. Mandatory Lint & Format Pipeline (Unconditional Gate)

MANDATORY — ALWAYS, WITHOUT REMINDERS: For EVERY Python file the agent writes, creates, or edits, the agent MUST run this pipeline before declaring the task complete. This gate is unconditional: it applies in addition to — and independently of — any project-level linting, formatter configuration, pre-commit hooks, or CI checks present in the target project. The agent MUST NOT skip it because "the project has its own linting", MUST NOT wait for the user to ask, and MUST NOT consider the task done until both stages pass on the agent's own changes.

The pipeline is Ruff-only (black, flake8, and isort are forbidden per the mandatory-tools skill) and has two mandatory stages, executed in this exact order:

  1. Format — ruff format (black-compatible automatic formatting).
  2. Lint — ruff check --fix (full-rule diagnostics WITH automatic in-place fixes; fixes scoped to the agent's own edits).

--fix is a mandatory part of the pipeline (HARD): the lint stage's FIRST invocation MUST carry --fix, letting Ruff rewrite auto-fixable violations in place. The agent MUST NOT hand-edit what ruff check --fix repairs mechanically — manual fixing of auto-fixable violations wastes tokens and energy and is a pipeline violation. Manual edits are reserved for diagnostics that --fix cannot repair.

The [*] reminder rule (HARD): the output line [*] fixable with the \--fix` option.means the previous run forgot--fix. On seeing it the agent MUST: (1) immediately recall that the first pass ALWAYS runs with --fix, and (2) immediately re-run the same command with --fix` — before reading or hand-fixing any diagnostic. Treat every occurrence as a self-check failure of this pipeline.

Hard Constraint: Foreign Code Isolation

  • ONLY format and fix violations in code you explicitly wrote or modified.
  • NEVER change unmodified ("foreign") code to satisfy the formatter or linter.
  • If a violation exists in unmodified code, ignore it completely.
  • If the linter suggests moving or refactoring that would affect unmodified code, skip the suggestion.
  • Run every pipeline command with an explicit file list (<changed_files>) — NEVER against the whole project, a whole directory, or files you did not touch.

Restoring Foreign Code After Formatting (MANDATORY)

Automatic formatters rewrite whole lines and may reformat code the agent never intended to touch. Foreign code MUST be returned to its exact prior state:

  1. Baseline first. Before running ruff format, make sure a restorable baseline exists for every target file (a git-tracked file with a committed or staged state, or an explicit backup copy). If git diff <file> cannot serve as the baseline for a target file, create a backup copy of it BEFORE formatting.
  2. Inspect every hunk. After formatting, run git diff <file> (or diff against the backup) and review each hunk individually.
  3. Revert foreign hunks. Any hunk that rewrites lines the agent did NOT author or intend to modify MUST be reverted (targeted git checkout -p, interactive hunk discard, or manual re-application) so foreign code becomes byte-identical to its baseline. NEVER blanket-revert: your own changes MUST survive.
  4. Re-verify. Re-run ruff format --check and ruff check on the file. If reverting a foreign hunk makes your own code fail the pipeline, re-apply formatting to your lines manually until both stages pass.
  5. Justify unavoidable bleed. If a formatter-mandated change physically cannot be limited to your own lines (for example, the formatter rewraps a construct that spans your edit), you MUST explicitly justify the deviation in your output per §1 (Deviation Justification).
  6. Final scope check. The delivered diff MUST contain formatting and lint changes ONLY within code the agent wrote or modified.

Step 3.1: Discover Target Python Version

Determine the project's target Python version before linting by executing:

uv run python -c "import sys; print(f'py{sys.version_info.major}{sys.version_info.minor}')"

Use this exact value for <PYVER> in the subsequent steps.

Step 3.2: Format Own Changes (Black-Compatible)

Run the formatter targeting ONLY the files you created or modified, then immediately perform the Restoring Foreign Code After Formatting procedure above:

uvx ruff format <changed_files>

<changed_files> is the explicit list of files the agent wrote or edited — nothing else. This stage replaces black: ruff format implements black-compatible formatting, and invoking black itself is forbidden.

Step 3.3: Fix and Read Linter Suggestions

Run the following command targeting ONLY the files you modified — the --fix flag is MANDATORY on this first lint pass (see the HARD rules above); Ruff rewrites fixable violations in place:

uvx ruff check --fix --select ALL --ignore D,CPY,DOC,EM101,ERA001,FBT001,FBT002,FIX001,FIX002,TD001,TD002,TD003,TD004,TD005,TRY003 --target-version <PYVER> --output-format concise <changed_files>

Read every REMAINING suggestion carefully (these are the ones --fix could not repair). Apply manual fixes ONLY to the code you altered.

Step 3.4: Preview Remaining Fixes

After applying fixes, confirm no auto-fixable violations remain — the emitted diff MUST be empty (any non-empty hunk is a fix you still owe or a foreign line you MUST NOT apply):

uvx ruff check --select ALL --ignore D,CPY,DOC,EM101,ERA001,FBT001,FBT002,FIX001,FIX002,TD001,TD002,TD003,TD004,TD005,TRY003 --target-version <PYVER> --diff <changed_files>

This previews would-be fixes only; final git-scope verification is §4 step 6.

Step 3.5: Rule Lookup

If you are uncertain about any rule code generated by the linter, use:

uvx ruff rule <RULE_CODE>

(Example: uvx ruff rule E501)

Pipeline Failure Handling (HARD)

If any pipeline command cannot run or errors out — uv/uvx/ruff missing, the target project is not uv-managed and uv run fails, Ruff crashes on a syntax error mid-edit — the agent MUST STOP, report the exact failure and its output to the user, and ask how to proceed. The gate is unconditional, but it is NEVER satisfied by silently skipping it or by substituting another linter (black, flake8, isort stay forbidden).


4. Master Execution Workflow

  1. Analyze Task: Determine the specific Python operations required.
  2. Component Reuse Check: Apply the §5 Component Reuse Rule before writing any code.
  3. Route: Run the §2 routing funnel over the references/ corpus (subject map → frontmatter cards → bounded extraction of the selected py-* sections).
  4. Code Generation: Write the code strictly adhering to the extracted rules, the reuse manifests, AND local file consistency.
  5. Lint & Format: Execute the full Mandatory Lint & Format Pipeline (§3), including foreign-code restoration, on every file the agent wrote or edited — unconditionally, without reminders, and regardless of any project-level linting.
  6. Final Verification: Confirm via git diff that no unmodified (foreign) code was altered before concluding the task; any formatter bleed into foreign lines must already be reverted or explicitly justified.

5. Component Reuse Rule

Before implementing any new Python module, class, or function, the agent MUST check whether the project root contains a .sdk/ directory.

5.1 Discovery

If .sdk/ exists, discover all reuse manifests with: fd -L -t f EXPORT.md .sdk/

Read every returned file before writing code.

5.2 Applying Manifests

Each EXPORT.md describes reusable components and the criteria for copying them whole. Apply those criteria strictly. After copying a module, replace the source package prefix with the target project's package prefix and run the Mandatory Lint & Format Pipeline (§3) only on the changed files.


6. Constants, Enums, Magic Values, and Data Carriers

[ref: #py-constants-enums]

This section is mandatory. It applies to every Python file the agent writes, edits, or reviews.

6.1 No magic values

  • A "magic value" is any numeric or string literal that carries semantic meaning outside the immediate syntax (e.g., 200, 404, "pending", 0.95, 86400, 1 << 41).
  • Magic values MUST NOT appear inline in expressions, comparisons, function arguments, or return values.
  • The only literals allowed inline are:
    • 0, 1, -1 when used as pure arithmetic/indexing identities.
    • True, False, None.
    • Mathematical identity values such as base=10 or radix=10, documented in the same line.

6.2 Use enums for categorical values

  • Categorical string values MUST be represented as StrEnum with auto():
    class Role(StrEnum):
        ADMIN = auto()
        USER = auto()
  • Categorical numeric values MUST be represented as Enum:
    class Priority(Enum):
        LOW = 1
        HIGH = 2
  • Bit flags and masks MUST be represented as IntFlag:
    class Permission(IntFlag):
        READ = auto()
        WRITE = auto()
  • Prefer auto() for every member whose concrete value is not semantically significant. When only some members need custom values, assign those explicitly and keep auto() for the rest. Do not hand-write every value just because one member requires a custom value:
    class ReconTarget(StrEnum):
        PROGRAMS_INDEX = "/programs"
        AUTHOR_INDEX = "/author"
        ARCHIVE_INDEX = "/archive"
        NEWS_SECTION = auto()
        OPINIONS_SECTION = auto()

6.3 Sentinel values

  • Do not use magic strings or numbers as sentinels (e.g., result = -1, name = "N/A", value = 999).
  • Use a dedicated enum member or a singleton sentinel object:
    class Result(Enum):
        FOUND = auto()
        NOT_FOUND = auto()

6.4 Module-level constants

  • Any semantic value that is not naturally an enum MUST be defined as a module-level ALL_CAPS constant.
  • Examples: TIMEOUT_SECONDS = 10.0, REFRESH_BUFFER_RATIO = 0.95, MAX_RETRIES = 3.
  • Constants MUST be placed near the top of the module, after imports.
  • Whenever several constants form a logical or semantic group — such as URL path prefixes, section identifiers, feature flags, or configuration keys — they SHOULD be grouped into a single enum instead of being declared as separate ALL_CAPS constants. Prefer StrEnum for string groups, Enum for numeric groups, and IntFlag for flags. This makes the grouping explicit, gives it a name, and prevents accidental mixing with unrelated constants.

6.5 Function-boundary constants

  • Literal[...] is allowed ONLY at boundaries where the value comes from outside the application and cannot yet be an enum (e.g., raw external API input, CLI flags).
  • Inside the application, categorical strings and numbers MUST be Enum/StrEnum members, not Literal.
  • If the value can be modeled as a dataclass or Pydantic model, use that instead of Literal.

6.6 HTTP status codes

  • HTTP status codes MUST NOT be written as bare integers.
  • If starlette is available, use from starlette import status and status.HTTP_200_OK.
  • Otherwise use http.HTTPStatus.OK from the standard library.
  • Never use 200, 201, 400, 404, 500, etc.

6.7 Data carriers

  • Functions in application code MUST NOT accept or return plain dict as their public contract.
  • Raw dict is allowed only as the immediate input to a parser/validator; it MUST be wrapped in a model or dataclass before crossing any application function boundary.
  • Inside the application, use frozen dataclass instances (@dataclass(frozen=True)).
  • At application boundaries (HTTP, files, env, external APIs, CLI input), use Pydantic models. If Pydantic is unavailable, use a dataclass with explicit validation.
  • argparse.Namespace and similar CLI parsers must be mapped to a dataclass or Pydantic model before use.
  • TypedDict is allowed ONLY as an exception, with the user's explicit approval, and only for dict-shaped data that cannot be a dataclass/Pydantic model.
  • NamedTuple/namedtuple is allowed for performance-oriented intermediate representations when the data has already been validated by Pydantic models or sourced from dataclasses. It MUST NOT be used as the primary boundary carrier.

6.8 No ** unpacking

  • The ** operator MUST NOT be used to unpack dictionaries into function arguments.
  • Every argument MUST be passed explicitly by name or position.
  • Bad: func(**kwargs), obj.method(**config_dict).
  • Good: func(name=user.name, role=user.role).

6.9 Examples

Bad:

if response.status_code == 200:
    ...
wait(0.95)

Good:

from starlette import status
if response.status_code == status.HTTP_200_OK:
    ...
wait(REFRESH_BUFFER_RATIO)

Bad:

def create_user(data: dict) -> dict:
    ...

Good:

@dataclass(frozen=True)
class UserCreate: ...

@dataclass(frozen=True)
class User: ...

def create_user(data: UserCreate) -> User:
    ...

6.10 Enforcement

  • Ruff rule PLR2004 catches many magic-value violations. Do not suppress it without explicit justification.
  • Run the §3 pipeline on every changed file; fix every PLR2004 by naming the value or converting it to an enum.
  • The agent MUST self-review new function signatures for bare dict, **kwargs, magic literals, and missing enum/data-carrier types before declaring the task complete.

7. Logging and Output

[ref: #py-logging]

  • Every Python file that produces any diagnostic, status, warning, or error output MUST define a module-level logger:
    logger = logging.getLogger(__name__)
  • print() and sys.stdout.write() are forbidden for logging, debugging, status, warning, or error output. Use logger.debug/info/warning/error/exception instead.
  • For the script's actual product output (e.g., a CLI reporter, a pipe-friendly tool), use print() by default. Use sys.stdout.write() only when precise control is needed (no newline, raw strings, performance).
  • Never swallow exceptions, errors, or unusual conditions silently. Log them at the appropriate level.
  • Use logger.exception(...) inside except blocks to capture the traceback.
  • Log messages must be concise and include relevant context (identifiers, paths, operation names); avoid dumping large objects or full tracebacks at INFO level.
  • At module load time, use logger.debug.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.