python-lang
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.
- License 许可
- BSD-3-Clause
- 所属仓库
- kalaverin/skills
- 最近更新
- 2026-11-15
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- python-lang
- runtime
- true
- version
- 0.1.0
- requires
- [ "frontmatter-protocol", "read-for-comments" ]
- triggers
- { "any": { "files": "fd -e py -e pyi --max-results 1 | wc -l | grep -q 1", "request": "python, питон" } }
- description
- 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.
02 资源文件 5
- 参考文档prompts/REFERENCE_STANDARD_ADDENDUM.md3.2 KB
- 参考文档README.md4.4 KB
- 参考文档references/01_language_rules.md41.2 KB
- 参考文档references/02_style_rules.md91.2 KB
- 参考文档references/03_personal_rules.md2.6 KB
03 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-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.
04 同仓库更多 Skills
todo-protocol
Mandatory protocol for using the SetTodoList tool. Governs when to create a todo list, how to update it without violating immutability rules, how to synchronize item status after every tool call, and the forbidden mutations. Always active.
subagents-protocol
Mandatory protocol for delegating work to built-in subagents (coder, explore, plan), also called our bots by users. Always active. Owns the context-hygiene delegation test (material vs answer, cost balance, warm-instance reuse), launch parameters (mandatory explicit `model`), the single-source model-selection table, answer budgets, degradation handling, the launch checklist, and the role library for delegated review/audit with intent routing (`references/roles.md`).
serena-protocol
MANDATORY skill for Serena (MCP) memory, knowledge base, and symbolic code exploration operations. Use whenever the agent needs to: read or write Serena memories, mutate or persist memory, explore code via symbolic MCP tools, resolve contradictions in stored knowledge, or follow memory metadata, naming, and routing conventions.
read-for-comments
Mandatory local standards library and archive. Before fetching any standard from the internet, the agent MUST check the Serena `standard/` archive and this skill's `references/` seed; after ANY standard-body download, the agent MUST archive it per the event-bound Archival Rule. Governs standard lookup, fetch, archival, and the family and full-body rules.
preflight-checklist
Mandatory session-initialization closer and Startup Gate audit. Always loaded. Runs EXACTLY ONCE at session start, after all skill loading completes: verifies Startup Gate completion with evidence (mirror sync, forced import, discovery, activation, memory priming, MCP declaration, think block), runs dynamic session checks derived from the active skill set (mode states, delegation readiness), and reports a compact evidence-backed verdict table to the user before the first task output. Any FAIL is fixed before proceeding.
markdown-protocol
MANDATORY skill for Markdown authoring rules and the Markdown Headings as a Public API standard. Always active. Governs how the agent writes and edits any Markdown file: line discipline, date format, frontmatter pairing, markers and anchors, heading identity (slugs, renames, uniqueness), section shape and size, deprecation, and the errata conformance queue. The full normative standard lives in references/specification.md with rationale in references/rationale.md.