python-best-practices
npx machina-cli add skill Taoidle/plan-cascade/python --openclawFiles (1)
SKILL.md
1.8 KB
Python Best Practices
Code Style
| Rule | Guideline |
|---|---|
| Formatter | ruff format or black |
| Linter | ruff check with strict rules |
| Type hints | Always for public APIs |
| Docstrings | Google 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
| Rule | Guideline |
|---|---|
| Specific exceptions | Never bare except: |
| Context managers | Use with for resources |
| Early return | Validate 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
| Pattern | Usage |
|---|---|
@dataclass | Data containers |
@property | Computed attributes |
| Generators | Memory-efficient iteration |
functools.cache | Memoization |
Anti-Patterns
| Avoid | Use Instead |
|---|---|
| Mutable default args | None default, create inside |
import * | Explicit imports |
| Global state | Dependency injection |
# Bad: def add(item, items=[]): ...
# Good:
def add(item, items=None):
items = items or []
items.append(item)
return items
Tools
| Tool | Purpose |
|---|---|
pytest | Testing |
ruff | Linting + formatting |
mypy | Type checking |
uv | Dependencies |
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
- Step 1: Run formatting and linting (ruff format, ruff check --strict) and apply formatting with Black when needed
- Step 2: Annotate public APIs with type hints and add Google/NumPy style docstrings
- 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