Get the FREE Ultimate OpenClaw Setup Guide →

python-clean-code

Scanned
npx machina-cli add skill mikeleg/mg-skills-marketplace/python-clean-code --openclaw
Files (1)
SKILL.md
3.9 KB

Python Clean Code

Write clean, maintainable Python code with proper structure and conventions.

When Triggered

When activated, immediately read the relevant reference files and apply guidelines without asking for confirmation:

  • For any Python code: Read references/coding-style.md
  • For project structure decisions: Read references/project-structure.md
  • For FastAPI/API projects: Read references/vertical-slice-api.md

Always apply these guidelines proactively and automatically.

Core Principles

  1. Type hints always - Every function signature and class attribute
  2. Self-explanatory code - Comments explain why, not what
  3. Small focused functions - Single responsibility, early returns
  4. Flat project structure - Virtual layers, not rigid folders

Quick Reference

Naming

variable_name = "snake_case"
CONSTANT_VALUE = "UPPER_SNAKE_CASE"
def function_name() -> None: ...
class ClassName: ...

Data Structures

# Small structures → dataclass
@dataclass
class Point:
    x: float
    y: float

# If Pydantic available → use it for validation
class UserCreate(BaseModel):
    email: str
    name: str = Field(min_length=1)

# Complex behavior → regular class
class OrderProcessor:
    def __init__(self, repo: Repository) -> None:
        self._repo = repo

Function Design

# ✅ Good: early return, clear naming
def get_user_discount(user: User, order: Order) -> Decimal:
    if not user or not order:
        return Decimal("0")

    if order.total <= MIN_ORDER_FOR_DISCOUNT:
        return Decimal("0")

    return VIP_DISCOUNT if user.is_vip else STANDARD_DISCOUNT


# ❌ Bad: nested, unclear
def calc(u, o):
    d = 0
    if u:
        if o:
            if o.total > 100:
                if u.is_vip:
                    d = 0.2
    return d

Expressive Conditions

# ✅ Extract complex conditions
is_business_hours = 9 <= current_hour <= 17
is_weekday = current_day < 6
can_process = is_business_hours and is_weekday and not is_holiday

if can_process:
    process_order()

Project Initialization

Generate new project scaffold:

python scripts/init_project.py my-project --output /path/to/dir

Creates:

my-project/
├── pyproject.toml
├── Makefile
├── src/my_package/
│   ├── base.py          # Abstract interfaces
│   ├── config.py        # Configuration
│   ├── entities/        # Domain models
│   ├── services/        # Business logic
│   ├── workflows/       # Orchestration
│   └── infrastructure/  # External systems
└── tests/

Reference Files

The following reference files are automatically consulted when this skill is triggered:

  • references/coding-style.md - Comprehensive Python coding conventions: naming, type hints, imports, docstrings, and best practices
  • references/project-structure.md - Clean architecture patterns, dependency injection, project layout, and common anti-patterns
  • references/vertical-slice-api.md - FastAPI vertical slice architecture for feature-based API organization

Code Review Checklist

Before completing Python code:

  • Type hints on all functions and class attributes
  • snake_case variables, PascalCase classes, UPPER_SNAKE_CASE constants
  • No magic numbers - use named constants
  • Functions do one thing, max 20-30 lines
  • Early returns instead of nested conditions
  • No comments explaining what code does
  • Imports grouped: stdlib → third-party → local

Source

git clone https://github.com/mikeleg/mg-skills-marketplace/blob/master/skills/python-clean-code/SKILL.mdView on GitHub

Overview

This skill enforces type hints, readable structure, and pragmatic clean architecture in Python. It guides code style, project layout, and review practices, triggered by Python file creation, code generation, scaffolding, or refactoring tasks.

How This Skill Works

When activated, it reads reference files and applies guidelines automatically. It consults references/coding-style.md, references/project-structure.md, and references/vertical-slice-api.md, then promotes core principles like type hints on all signatures and attributes, self-explanatory comments, small focused functions, and a flat project structure.

When to Use It

  • Starting a new Python project from scratch
  • Refactoring an existing Python codebase for clarity
  • Reviewing Python implementations for consistency and architecture
  • Generating Python code or scaffolding a project
  • Applying clean architecture practices during Python development

Quick Start

  1. Step 1: Run a project initializer to scaffold a new Python project
  2. Step 2: Read references/coding-style.md, references/project-structure.md, and references/vertical-slice-api.md and apply guidelines
  3. Step 3: Implement code with type hints, clear names, small functions, and a flat package structure

Best Practices

  • Always annotate with type hints on all functions and class attributes
  • Use snake_case for variables, PascalCase for classes, and UPPER_SNAKE_CASE for constants
  • Avoid magic numbers by introducing named constants
  • Keep functions small and focused with single responsibility and 20-30 lines max
  • Prefer early returns and minimize nested conditionals

Example Use Cases

  • Initialize a new project scaffold with pyproject.toml and a src/my_package layout including base, config, entities, services, workflows, and infrastructure
  • Refactor a data model to a dataclass for simple structures
  • Add Pydantic models for input validation when available
  • Introduce a small class like OrderProcessor with dependency injection for repositories
  • Review a module to align naming conventions across snake_case, PascalCase, and UPPER_SNAKE_CASE

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers