Python coding best practices, conventions, and architectural patterns for production-ready applications. Use when writing, reviewing, or refactoring Python code to apply modern patterns and idiomatic style. Covers: general Python conventions (PEP 8, type hints, testing with pytest/Hypothesis/Faker), FastAPI best practices (async endpoints, error handling, OpenAPI docs, dependency injection), dataframe mindset (vectorization, columnar operations, method chaining across Pandas/Polars/DuckDB/Spark), and Python data model (dunder methods, iterators, context managers, descriptors, properties). Applicable to Python 3.12+ projects using pyproject.toml and Ruff for linting.
Load the relevant reference when the task involves these domains:
fastapi skill for project setup, endpoints, error handling, and Pydantic integration__iter__/__next__, __enter__/__exit__, descriptors, @property, native-feeling APIsruff check --fix . && ruff format .list[str], dict[str, int]), not typing.List/typing.Dict# Files: snake_case
mcp_server.py
# Classes: PascalCase
class CustomerQueryTool:
# Functions/variables: snake_case
async def analyze_customer_query():
server_config = get_config()
# Constants: SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
Use this layout for new Python projects:
project-name/
├── pyproject.toml # Project metadata, dependencies, tool config
├── src/
│ └── package_name/
│ ├── __init__.py
│ ├── main.py
│ └── models.py
├── tests/
│ ├── conftest.py # Shared fixtures
│ └── test_main.py
└── README.md
src/ layout to prevent accidental imports of uninstalled codepyproject.tomluv for dependency management; fall back to pipAlways use python-dotenv for environment variable management. Include it in project dependencies and call load_dotenv() at the application entry point before any os.environ access.
python-dotenv to [project.dependencies] in pyproject.tomlload_dotenv() once at the top of the entry point (main.py), never inside library code.env to .gitignore; commit a .env.example with placeholder values for documentationos.environ["KEY"] (not os.getenv) to fail fast on missing required valuespydantic-settings (BaseSettings with env_file)# main.py — entry point
from dotenv import load_dotenv
load_dotenv() # must precede any os.environ access
import os
DATABASE_URL = os.environ["DATABASE_URL"]
API_KEY = os.environ["API_KEY"]
conftest.py for shared fixtures@pytest.mark.parametrize for input variationFaker() for generating realistic test datahypothesis for property-based testing of pure functionsschemathesis for property-based testing of API endpointspytest-snapshot for snapshot testing API responsespytest-cov; write tests for uncovered paths# Example: parametrized test with fixture
@pytest.fixture
def sample_user(faker):
return {"name": faker.name(), "email": faker.email()}
@pytest.mark.parametrize("quantity,expected", [(0, 0), (5, 50), (-1, ValueError)])
def test_calculate_total(quantity, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
calculate_total(price=10, quantity=quantity)
else:
assert calculate_total(price=10, quantity=quantity) == expected
Run pip-audit before adding or upgrading any dependency. Pin exact versions in production. Treat every third-party package as an attack surface — see references/security.md for CVE checking workflow, supply chain attack patterns, CI automation, and emergency response.
Exceptionwith), not bare try/finallySearch for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer