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.
In this repository17 other files it gives its agents.
- AGENTS.mdAGENTS.md
- api-designSkill
- bootstrapSkill
- dash-protocolSkill
- discuss-firstSkill
- entity-protocolSkill
- existence-bibleSkill
- frontmatter-protocolSkill
- kagi-searchSkill
- mandatory-toolsSkill
- markdown-protocolSkill
- ondemandSkill
- preflight-checklistSkill
- read-for-commentsSkill
- serena-protocolSkill
- subagents-protocolSkill
- todo-protocolSkill
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
- Distinctive: line 24
Deviation Justification: If you deviate from any MUST directive, you MUST explicitly justify the deviation in your output.
- Very specific: line 45
Run the subject map (Command 1) over references/ and shortlist candidate files semantically — the request plus inferred session work.
- Very specific: line 46
Read the full frontmatter of shortlisted files — 03_personal_rules.md is always shortlisted — and match every card's what / use_when / …
- Distinctive: line 68
If a violation exists in unmodified code, ignore it completely.
- Distinctive: line 69
If the linter suggests moving or refactoring that would affect unmodified code, skip the suggestion.
- Very specific: line 70
Run every pipeline command with an explicit file list (<changed_files>) — NEVER against the whole project, a whole directory, or files you …
- Very specific: line 76
Inspect every hunk: After formatting, run git diff <file> (or diff against the backup) and review each hunk individually.
- Distinctive: line 79
Justify unavoidable bleed: If a formatter-mandated change physically cannot be limited to your own lines (for example, the formatter …
- Distinctive: line 90
Run the formatter targeting ONLY the files you created or modified, then immediately perform the Restoring Foreign Code After Formatting …
- Very specific: line 97
Run the following command targeting ONLY the files you modified — the --fix flag is MANDATORY on this first lint pass (see the HARD rules …
- Very specific: line 101
Read every REMAINING suggestion carefully (these are the ones --fix could not repair).
- Distinctive: line 104
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 …
- Distinctive: line 111
If you are uncertain about any rule code generated by the linter, use:
- Very specific: line 125
Route: Run the §2 routing funnel over the references/ corpus (subject map → frontmatter cards → bounded extraction of the selected py-* …
- Distinctive: line 126
Code Generation: Write the code strictly adhering to the extracted rules, the reuse manifests, AND local file consistency.
- Very specific: line 134
Before implementing any new Python module, class, or function, the agent MUST check whether the project root contains a .sdk/ directory.
- Very specific: line 137
If .sdk/ exists, discover all reuse manifests with: fd -L -t f EXPORT.md .sdk/
- Distinctive: line 139
Read every returned file before writing code.
- Distinctive: line 144
After copying a module, replace the source package prefix with the target project's package prefix and run the Mandatory Lint & Format …
- Very specific: line 183
Prefer auto() for every member whose concrete value is not semantically significant.
- Very specific: line 195
Do not use magic strings or numbers as sentinels (e.g., result = -1, name = "N/A", value = 999).
- Distinctive: line 196
Use a dedicated enum member or a singleton sentinel object:
- Very specific: line 214
If the value can be modeled as a dataclass or Pydantic model, use that instead of Literal.
- Very specific: line 219
If starlette is available, use from starlette import status and status.HTTP_200_OK.
- Very specific: line 221
Never use 200, 201, 400, 404, 500, etc.
- Distinctive: line 236
Every argument MUST be passed explicitly by name or position.
- Very specific: line 278
Run the §3 pipeline on every changed file.
- Distinctive: line 287
Every Python file that produces any diagnostic, status, warning, or error output MUST define a module-level logger:
- Distinctive: line 293
Never swallow exceptions, errors, or unusual conditions silently.
- Very specific: line 294
Use logger.exception(...) inside except blocks to capture the traceback.
≈ “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.
Files
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-designskill. - RFC Verbs: For precise semantics of requirement-level verbs, consult the
read-for-commentsskill.
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, anchorspy-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, anchorspy-st-*.references/03_personal_rules.md— project-specific rules that EXTEND and OVERRIDE the Google corpora on conflict, anchorspy-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]):
- Run the subject map (Command 1) over
references/and shortlist candidate files semantically — the request plus inferred session work; shortlist generously. - Read the full frontmatter of shortlisted files —
03_personal_rules.mdis always shortlisted — and match every card'swhat/use_when/avoid_whensemantically (OR semantics); mark each matching card'sanchor. - Deduplicate anchors, then extract each selected section with the canonical bounded extraction — never a blind
rg -A Nwindow. - 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:
- Format —
ruff format(black-compatible automatic formatting). - 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:
- 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). Ifgit diff <file>cannot serve as the baseline for a target file, create a backup copy of it BEFORE formatting. - Inspect every hunk. After formatting, run
git diff <file>(or diff against the backup) and review each hunk individually. - 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. - Re-verify. Re-run
ruff format --checkandruff checkon 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. - 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).
- 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
- Analyze Task: Determine the specific Python operations required.
- Component Reuse Check: Apply the §5 Component Reuse Rule before writing any code.
- Route: Run the §2 routing funnel over the
references/corpus (subject map → frontmatter cards → bounded extraction of the selectedpy-*sections). - Code Generation: Write the code strictly adhering to the extracted rules, the reuse manifests, AND local file consistency.
- 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.
- Final Verification: Confirm via
git diffthat 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,-1when used as pure arithmetic/indexing identities.True,False,None.- Mathematical identity values such as
base=10orradix=10, documented in the same line.
6.2 Use enums for categorical values
- Categorical string values MUST be represented as
StrEnumwithauto():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 keepauto()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_CAPSconstant. - 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_CAPSconstants. PreferStrEnumfor string groups,Enumfor numeric groups, andIntFlagfor 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/StrEnummembers, notLiteral. - 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
starletteis available, usefrom starlette import statusandstatus.HTTP_200_OK. - Otherwise use
http.HTTPStatus.OKfrom 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
dictas their public contract. - Raw
dictis 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
dataclassinstances (@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.Namespaceand similar CLI parsers must be mapped to a dataclass or Pydantic model before use.TypedDictis 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/namedtupleis 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
PLR2004catches many magic-value violations. Do not suppress it without explicit justification. - Run the §3 pipeline on every changed file; fix every
PLR2004by 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()andsys.stdout.write()are forbidden for logging, debugging, status, warning, or error output. Uselogger.debug/info/warning/error/exceptioninstead.- For the script's actual product output (e.g., a CLI reporter, a pipe-friendly tool), use
print()by default. Usesys.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(...)insideexceptblocks 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
INFOlevel. - At module load time, use
logger.debug.
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
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.

