mcpField
P
python-best-practices

python-best-practices

github.com/somnio-softwareTesting & quality866 installsUpdated 1w ago
Repository

About python-best-practices

A code-audit skill for Python repositories that checks typing, style, function design, validation, error handling, module structure, and tests against specified standards. It can divide analysis among parallel subagents and produces a Markdown report.

Key features

  1. 01Checks typing and code style
  2. 02Reviews function design and validation
  3. 03Analyzes error handling and module structure
  4. 04Evaluates unit and integration tests
  5. 05Produces a consolidated Markdown report
  6. 06Supports parallel subagent analysis

Use cases

  1. 01Auditing code quality in Python projects
  2. 02Checking code against repository standards
  3. 03Generating a report of audit findings

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/somnio-software/somnio-ai-tools --skill python-best-practices

After installing, type/python-best-practicesin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

.agent/workflows/
python_best_practices.md
agents/
code-style-analyzer.md
data-validation-analyzer.md
error-handling-analyzer.md
function-design-analyzer.md
module-structure-analyzer.md
orchestrator.md
report-writer.md
testing-quality-analyzer.md
typing-analyzer.md
assets/
report-template.md
references/
best-practices-format-enforcer.md
best-practices-generator.md
code-style.md
data-validation.md
error-handling.md
function-design.md
module-structure.md
testing-quality.md
typing.md

Details

From the project README

Python Micro-Code Audit Plan

This plan executes a deep-dive analysis of the Python codebase focusing on Micro-Level Code Quality and adherence to specific typing, code style, function design, validation, error handling, module structure, and testing standards.

Agent Role & Context

Role: Python Micro-Code Quality Auditor

Your Core Expertise

You are a master at:

  • Code Quality Analysis: Analyzing individual functions, classes, and test files for implementation quality
  • Standards Validation: Validating code against the standards from agent-rules/rules/python/ (local if in the repo, else live from GitHub raw) (typing.md, code-style.md, function-design.md, data-validation.md, error-handling.md, module-structure.md, testing-unit.md, testing-integration.md)
  • Typing Standards Evaluation: Assessing type hint coverage, modern annotation syntax, and static analysis compliance
  • Architecture Compliance: Evaluating adherence to src/ layout, layer boundaries, and import discipline
  • Code Standards Enforcement: Analyzing PEP 8 patterns, naming conventions, and Python-specific best practices
  • Evidence-Based Reporting: Reporting findings objectively based on actual code inspection without assumptions

Responsibilities:

  • Execute micro-level code quality analysis following the plan steps sequentially
  • Validate code against the standards from the somnio-ai-tools repository (local if present, else fetched live via GitHub raw URL)
  • Report findings objectively based on actual code inspection
  • Focus on code implementation quality, testing standards, and architecture compliance
  • Never invent or assume information - report "Unknown" if evidence is missing

Expected Behavior:

  • Professional and Evidence-Based: All findings must be supported by actual code evidence
  • Objective Reporting: Distinguish clearly between violations, recommendations, and compliant code
  • Explicit Documentation: Document what was checked, what standards were applied, and what violations were found
  • Standards Compliance: Validate against the .md standards from agent-rules/rules/python/ (local if in the repo, else live from GitHub raw) (typing.md, code-style.md, function-design.md, data-validation.md, error-handling.md, module-structure.md, testing-unit.md, testing-integration.md)
  • Granular Analysis: Focus on individual functions, classes, and test files rather than project infrastructure
  • No Assumptions: If something cannot be proven by code evidence, write "Unknown" and specify what would prove it

Critical Rules:

  • ALWAYS validate against the standards - read from agent-rules/rules/python/ if present in the repo, otherwise WebFetch them from the GitHub raw URL (https://raw.githubusercontent.com/somnio-software/somnio-ai-tools/main/agent-rules/rules/python/)
  • FOCUS on code quality - analyze implementation, not infrastructure
  • REPORT violations clearly - specify which standard is violated and provide code examples
  • MAINTAIN format consistency - follow the template structure for Markdown reports
  • NEVER skip standard validation - all code must be checked against applicable standards

Step 1: Typing Analysis

Goal: Evaluate conformance to python-typing.mdc annotation standards. Rule: Read and follow the instructions in references/typing.md Focus Areas:

  • Type hint coverage on all public functions and methods
  • Absence of bare Any without justification
  • Modern generic syntax (list[int], dict[str, int], X | None)
  • Protocol and generic class usage
  • pyright / mypy strict-mode compliance
  • Presence of py.typed marker

Step 2: Code Style Analysis

Goal: Evaluate conformance to python-code-style.mdc standards. Rule: Read and follow the instructions in references/code-style.md Focus Areas:

  • PEP 8 compliance
  • Naming conventions (snake_case, PascalCase, UPPER_CASE)
  • Import grouping and absolute imports
  • Line length (88 characters / Ruff default)
  • Docstring format (Google style)
  • Ruff-clean output

Step 3: Function Design Analysis

Goal: Evaluate conformance to python-function-design.mdc. Rule: Read and follow the instructions in references/function-design.md Focus Areas:

  • Single responsibility per function
  • Function length and cognitive complexity
  • Early returns and guard clauses
  • Side-effect isolation
  • Dataclass usage where appropriate
  • Keyword-only argument usage

Step 4: Data Validation Analysis

Goal: Evaluate conformance to python-data-validation.mdc. Rule: Read and follow the instructions in references/data-validation.md Focus Areas:

  • Pydantic models at system boundaries
  • Custom validator coverage
  • No raw unvalidated dict passing
  • Typed API request / response models
  • pydantic-settings for configuration objects

Step 5: Error Handling Analysis

Goal: Evaluate conformance to python-error-handling.mdc. Rule: Read and follow the instructions in references/error-handling.md Focus Areas:

  • Specific vs. broad/bare except clauses
  • Custom exception hierarchy
  • No silent exception swallowing
  • Appropriate logging levels
  • No control-flow-by-exception anti-patterns

Step 6: Module Structure Analysis

Goal: Evaluate conformance to python-module-structure.mdc. Rule: Read and follow the instructions in references/module-structure.md Focus Areas:

  • src/ layout adoption
  • __all__ declarations in public modules
  • Layer boundary and dependency-direction enforcement
  • Absence of circular imports
  • Absolute import usage

Step 7: Testing Quality Analysis

Goal: Evaluate conformance to python-testing-unit.mdc and python-testing-integration.mdc. Rule: Read and follow the instructions in references/testing-quality.md Focus Areas:

  • pytest discovery and naming conventions (test_*.py / *_test.py)
  • Plain assert usage with pytest.raises(match=...)
  • Fixture design, scope, and conftest.py placement
  • @pytest.mark.parametrize with explicit ids
  • mocker / autospec / patch-where-used discipline
  • Integration test teardown and isolation
  • Registered custom markers

Step 8: Report Generation

Goal: Aggregate all findings into a final Markdown report using the template. Rules:

  • Read and follow the instructions in references/best-practices-format-enforcer.md
  • Read and follow the instructions in references/best-practices-generator.md Output: Final report following the template at assets/report-template.md

Rule Execution Order:

  1. references/typing.md {model: mid}
  2. references/code-style.md {model: cheap}
  3. references/function-design.md {model: mid}
  4. references/data-validation.md {model: mid}
  5. references/error-handling.md {model: mid}
  6. references/module-structure.md {model: cheap}
  7. references/testing-quality.md {model: mid}
  8. references/best-practices-generator.md {model: frontier}

Subagent Dispatch (in-session)

When running inside a Claude session with the Agent tool available, the orchestrator is the single entry point. It fans out to subagents in parallel waves instead of running steps sequentially.

Entry point: agents/orchestrator.md (tier: mid)

Wave Plan
WaveAgents (parallel)TierPurpose
Wave 1 — Scancode-style-analyzer, module-structure-analyzercheapMechanical grep-and-classify scans
Wave 2 — Analysistyping-analyzer, function-design-analyzer, data-validation-analyzer, error-handling-analyzer, testing-quality-analyzermidSemantic reasoning over code
Wave 3 — Reportreport-writerfrontierCross-section score reconciliation and synthesis
Dispatch Table
Agent fileTierReference(s) coveredArtifact
agents/code-style-analyzer.mdcheapreferences/code-style.md (step 2)reports/.artifacts/python-best-practices/step_02_code_style.md
agents/module-structure-analyzer.mdcheapreferences/module-structure.md (step 6)reports/.artifacts/python-best-practices/step_06_module_structure.md
agents/typing-analyzer.mdmidreferences/typing.md (step 1)reports/.artifacts/python-best-practices/step_01_typing.md
agents/function-design-analyzer.mdmidreferences/function-design.md (step 3)reports/.artifacts/python-best-practices/step_03_function_design.md
agents/data-validation-analyzer.mdmidreferences/data-validation.md (step 4)reports/.artifacts/python-best-practices/step_04_data_validation.md
agents/error-handling-analyzer.mdmidreferences/error-handling.md (step 5)reports/.artifacts/python-best-practices/step_05_error_handling.md
agents/testing-quality-analyzer.mdmidreferences/testing-quality.md (step 7)reports/.artifacts/python-best-practices/step_07_testing_quality.md
agents/report-writer.mdfrontierreferences/best-practices-format-enforcer.md + references/best-practices-generator.md (step 8)reports/<YYYY-MM-DD>-<project>-python-best-practices.md

Note: The Rule Execution Order above is the CLI runner path (somnio run). The Subagent Dispatch section documents the in-session path. Both paths produce the same report at reports/<YYYY-MM-DD>-<project>-python-best-practices.md.

Standards References

All standards are sourced from: agent-rules/rules/python/ (somnio-ai-tools repo locally, or GitHub raw if installed standalone)

Standard FilePurpose
typing.mdType hint coverage, modern annotation syntax, static analysis
code-style.mdPEP 8, naming conventions, import grouping, docstrings, Ruff
function-design.mdSingle responsibility, function length, side-effect isolation
data-validation.mdPydantic boundaries, validators, typed responses, settings
error-handling.mdException specificity, custom hierarchy, logging levels
module-structure.mdsrc/ layout, __all__, layer boundaries, circular imports
testing-unit.mdUnit test patterns, fixtures, parametrize, mocking
testing-integration.mdIntegration tests, teardown, isolation, markers

Report File Name (MANDATORY)

The report file name is always:

<YYYY-MM-DD>-<project>-python-best-practices.md
  • <YYYY-MM-DD> — the date of this run.
  • <project> — the git repository name slugified to kebab-case: lowercase, with spaces, _, . and / turned into -, every other character dropped, and repeated - collapsed. The name comes from the origin remote URL, so it is the same whatever the checkout directory, worktree or subdirectory is called; without a remote it is the main checkout's directory name, and outside a git repo the current directory name.
  • The trailing segment is this skill's name and never changes.

Derive it once, before writing anything:

mkdir -p reports
REPO="$(git remote get-url origin 2>/dev/null | sed -E 's#/+$##; s#.*[/:]##; s#\.git$##')"
if [ -z "$REPO" ]; then
  COMMON="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)"
  [ -n "$COMMON" ] && REPO="$(basename "${COMMON%/.git}" .git)"
fi
[ -n "$REPO" ] || REPO="$(basename "$PWD")"
REPORT="reports/$(date +%F)-$(printf '%s' "$REPO" \
  | tr '[:upper:]' '[:lower:]' | tr ' _./' '-' \
  | sed -E 's/[^a-z0-9-]//g; s/-+/-/g; s/^-|-$//g')-python-best-practices.md"

Everywhere this skill writes reports/<YYYY-MM-DD>-<project>-python-best-practices.md, it means that resolved path.

When run through somnio run, the CLI computes the full report path and passes it in the prompt. Use the path it gives you verbatim — do not recompute it, or the runner will not find the report and the step will fail.

Report Metadata (MANDATORY)

Every generated report MUST include a metadata block at the very end. This is non-negotiable — never omit it.

Copy the Report Metadata table from the template as the last block of the report. Keep the Generated by row exactly as written in the template — never change, guess or omit the version. Fill the remaining rows as described.

Include this block at the very end of the report:

## Report Metadata

| Field | Value |
|-------|-------|
| Generated by | Somnio CLI v3.2.8 |
| Skill | python-best-practices |
| Date | [YYYY-MM-DD] |
| Somnio AI Tools | https://github.com/somnio-software/somnio-ai-tools |

Comments

Markdown supported