Get the FREE Ultimate OpenClaw Setup Guide →

python-best-practices

npx machina-cli add skill Taoidle/plan-cascade/python --openclaw
Files (1)
SKILL.md
1.8 KB

Python Best Practices

Code Style

RuleGuideline
Formatterruff format or black
Linterruff check with strict rules
Type hintsAlways for public APIs
DocstringsGoogle or NumPy style

Type Hints

def process(items: list[str], max_count: int = 10) -> dict[str, int]: ...
def find_user(user_id: int) -> User | None: ...

Error Handling

RuleGuideline
Specific exceptionsNever bare except:
Context managersUse with for resources
Early returnValidate inputs, fail fast
# Good
try:
    result = process(data)
except ValidationError as e:
    logger.warning(f"Validation failed: {e}")
    return default

Project Structure

src/package_name/
├── __init__.py
├── core/
└── py.typed
tests/
├── conftest.py
└── test_*.py
pyproject.toml

Common Patterns

PatternUsage
@dataclassData containers
@propertyComputed attributes
GeneratorsMemory-efficient iteration
functools.cacheMemoization

Anti-Patterns

AvoidUse Instead
Mutable default argsNone default, create inside
import *Explicit imports
Global stateDependency injection
# Bad: def add(item, items=[]): ...
# Good:
def add(item, items=None):
    items = items or []
    items.append(item)
    return items

Tools

ToolPurpose
pytestTesting
ruffLinting + formatting
mypyType checking
uvDependencies

Source

git clone https://github.com/Taoidle/plan-cascade/blob/master/builtin-skills/python/SKILL.mdView on GitHub

Overview

This skill codifies Python coding best practices to improve readability, maintainability, and robustness. It emphasizes type hints for public APIs, rigorous error handling, Google/NumPy style docstrings, and common patterns like dataclasses, properties, generators, and memoization, while warning against mutable defaults, wildcard imports, and global state.

How This Skill Works

The guideline set covers Code Style, Type Hints, Error Handling, Project Structure, and Tools. Developers apply these rules when writing or reviewing Python code, leveraging tooling such as ruff, black, mypy, pytest, and uv to enforce standards and catch issues early.

When to Use It

  • Starting a new Python module or adding public APIs
  • Reviewing code to ensure proper type hints and clear docstrings
  • Refactoring to adopt common patterns like @dataclass, @property, or generators
  • Auditing error handling to avoid bare excepts and ensure fail-fast validation
  • Setting up and using tooling (ruff, mypy, pytest, uv) to enforce standards

Quick Start

  1. Step 1: Run formatting and linting (ruff format, ruff check --strict) and apply formatting with Black when needed
  2. Step 2: Annotate public APIs with type hints and add Google/NumPy style docstrings
  3. Step 3: Apply common patterns (dataclass, property, generators, cache) and verify with tests and type checks (pytest, mypy)

Best Practices

  • Always include type hints for public APIs
  • Use Google or NumPy style docstrings for clarity
  • Use with for resources (context managers) to manage setup/teardown
  • Prefer early return and input validation to fail fast
  • Leverage common patterns: @dataclass, @property, generators, and functools.cache

Example Use Cases

  • def process(items: list[str], max_count: int = 10) -> dict[str, int]: ...
  • def find_user(user_id: int) -> User | None: ...
  • with open('data.txt', 'r') as f: content = f.read()
  • from dataclasses import dataclass @dataclass class User: id: int name: str
  • @cache def expensive_computation(x: int) -> int: # memoized computation for performance return x * x

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers