Skip to main content
skill CX Codex

python-best-practices · rohitg00 — Claude Code skill: what it does

python-best-practices guides Claude Code toward modern Python style: type hints, dataclasses, async code, project layout and pytest setup.

Apache-2.0 ★ 2,858 updated 2026-05-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add rohitg00/awesome-claude-code-toolkit --skill python-best-practices -a claude-code
Open on GitHub

What python-best-practices does

The skill lays out conventions for Python code: 3.12-style type hints (list[str], User | None, type Vector[T]), a rule for picking dataclass versus Pydantic depending on whether data is internal or comes from outside, and async patterns built on httpx with asyncio.gather and asyncio.Semaphore for concurrency limits.

It also covers a src-based project layout, pyproject.toml configuration using Ruff and mypy in place of separate flake8, isort and black tools, dependency management with uv, and pytest setup with shared fixtures in conftest.py and AsyncMock for mocking. Blocking I/O inside async functions is flagged as something to route through asyncio.to_thread instead.

This is a set of coding conventions and snippets rather than a runnable tool: it shapes how Claude Code writes Python but does not execute linters or tests on its own.

What it helps with

  • apply modern type hint syntax across a Python 3.12 codebase
  • decide between dataclass and Pydantic for a given model
  • write async code with httpx under a concurrency limit
  • configure pyproject.toml with Ruff and mypy instead of separate linters
  • set up pytest with fixtures and mocked HTTP clients

Example prompts for the agent

  • Rewrite this class as a frozen, slotted dataclass
  • Set up pyproject.toml following the python-best-practices rules
  • Write an async function that fetches users via httpx with a semaphore limit

How to install python-best-practices

1Skills CLI (Vercel)

npx skills add rohitg00/awesome-claude-code-toolkit --skill python-best-practices -a claude-code

2Manually: put the files in place

~/.claude/skills/python-best-practices/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/python-best-practices/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about python-best-practices

How do I install python-best-practices in Claude Code?

Run npx skills add rohitg00/awesome-claude-code-toolkit --skill python-best-practices -a claude-code; the skill lands in ~/.claude/skills/python-best-practices/SKILL.md.

What does the python-best-practices skill do?

It sets conventions for Python code: modern type hints, a dataclass-versus-Pydantic rule, async patterns with httpx, project structure and pytest configuration.

When does it recommend dataclass over Pydantic?

Dataclasses are for internal domain models that need no validation, while Pydantic covers API boundaries, config files and parsing of external input with field checks.

Source text

SKILL.md · Apache-2.0
---
name: python-best-practices
description: Pythonic code with modern type hints, dataclasses, async patterns, packaging, and testing
---

# Python Best Practices

## Type Hints (3.12+ Syntax)

```python
# Use built-in generics (3.9+), no need for typing.List, typing.Dict
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Union with | syntax (3.10+)
def find_user(user_id: int) -> User | None:
    ...

# Type parameter syntax (3.12+)
type Vector[T] = list[T]
type Matrix[T] = list[Vector[T]]

def first[T](items: list[T]) -> T:
    return items[0]

# TypedDict for structured dicts
from typing import TypedDict

class UserResponse(TypedDict):
    id: int
    name: str
    email: str
    active: bool
```

Always type function signatures. Use `mypy --strict` or `pyright` in CI. Use `type: ignore` comments sparingly with justification.

## Dataclasses vs Pydantic

### Dataclasses (internal data, no validation needed)
```python
from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

@dataclass
class Config:
    host: str = "localhost"
    port: int = 8080
    tags: list[str] = field(default_factory=list)
```

Use `frozen=True` for immutable value objects. Use `slots=True` for memory efficiency.

### Pydantic (external input, validation required)
```python
from pydantic import BaseModel, Field, field_validator

class CreateUserRequest(BaseModel):
    model_config = {"strict": True}

    email: str = Field(max_length=255)
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=13, le=150)

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("Invalid email format")
        return v.lower()
```

Rule: Use dataclasses for domain models and internal structs. Use Pydantic for API boundaries, config files, and external data parsing.

## Async Patterns

```python
import asyncio
import httpx

async def fetch_user(client: httpx.AsyncClient, user_id: int) -> User:
    response = await client.get(f"/users/{user_id}")
    response.raise_for_status()
    return User(**response.json())

async def fetch_all_users(user_ids: list[int]) -> list[User]:
    async with httpx.AsyncClient(base_url="https://api.example.com") as client:
        tasks = [fetch_user(client, uid) for uid in user_ids]
        return await asyncio.gather(*tasks)

async def process_with_semaphore(items: list[str], max_concurrent: int = 10):
    semaphore = asyncio.Semaphore(max_concurrent)
    async def bounded_process(item: str):
        async with semaphore:
            return await process_item(item)
    return await asyncio.gather(*[bounded_process(i) for i in items])
```

Rules:
- Use `httpx` instead of `requests` for async HTTP
- Use `asyncio.gather` for concurrent tasks, `asyncio.Semaphore` for rate limiting
- Never call blocking I/O in async functions (use `asyncio.to_thread` for legacy code)
- Use `async with` for resource management (connections, sessions)

## Project Structure

```
my-project/
  src/
    my_project/
      __init__.py
      main.py
      models.py
      services/
        __init__.py
        user_service.py
      api/
        __init__.py
        routes.py
  tests/
    conftest.py
    test_models.py
    test_services/
      test_user_service.py
  pyproject.toml
```

Use `src` layout to prevent accidental imports from the project root.

## pyproject.toml

```toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.27",
    "pydantic>=2.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0",
    "pytest-cov",
    "pytest-asyncio",
    "mypy",
    "ruff",
]

[project.scripts]
my-project = "my_project.main:cli"

[tool.ruff]
line-length = 100
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "SIM", "RUF"]

[tool.mypy]
strict = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
```

Use `pyproject.toml` for all tool configuration. Use Ruff instead of flake8 + isort + black (single tool, 10-100x faster).

## Virtual Environments

```bash
# Use uv for fast dependency management
uv venv
uv pip install -e ".[dev]"

# Or standard venv
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
```

Always use virtual environments. Never install packages globally. Pin exact versions in a lockfile (`uv.lock` or `requirements.txt` generated from `pip freeze`).

## Testing with pytest

```python
import pytest
from unittest.mock import AsyncMock, patch

@pytest.fixture
def user_service(db_session):
    return UserService(session=db_session)

async def test_create_user_returns_user_with_hashed_password(user_service):
    user = await user_service.create(email="[email protected]", password="secret")
    assert user.email == "[email protected]"
    assert user.password_hash != "secret"

async def test_create_user_rejects_duplicate_email(user_service):
    await user_service.create(email="[email protected]", password="secret")
    with pytest.raises(DuplicateEmailError):
        await user_service.create(email="[email protected]", password="other")

@pytest.fixture
def mock_http_client():
    client = AsyncMock(spec=httpx.AsyncClient)
    client.get.return_value = httpx.Response(200, json={"id": 1, "name": "Alice"})
    return client

async def test_fetch_user_parses_response(mock_http_client):
    user = await fetch_user(mock_http_client, user_id=1)
    assert user.name == "Alice"
    mock_http_client.get.assert_called_once_with("/users/1")
```

Use `conftest.py` for shared fixtures. Use `pytest.mark.parametrize` for test variations. Use `tmp_path` fixture for file system tests.

## Pythonic Idioms

```python
# Unpacking
first, *rest = items
x, y = point

# Comprehensions over map/filter
squares = [x**2 for x in numbers if x > 0]
lookup = {u.id: u for u in users}

# Context managers for resource cleanup
with open(path) as f:
    data = f.read()

# Walrus operator for assign-and-test
if (match := pattern.search(text)) is not None:
    process(match.group(1))

# Structural pattern matching (3.10+)
match command:
    case {"action": "move", "direction": d}:
        move(d)
    case {"action": "quit"}:
        sys.exit(0)
    case _:
        raise ValueError(f"Unknown command: {command}")
```

## Error Handling

```python
class AppError(Exception):
    def __init__(self, message: str, code: str):
        super().__init__(message)
        self.code = code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} {id} not found", "NOT_FOUND")

# Specific exceptions, never bare except
try:
    user = await get_user(user_id)
except NotFoundError:
    return {"error": "User not found"}, 404
except DatabaseError as e:
    logger.exception("Database error fetching user")
    return {"error": "Internal error"}, 500
```

Never use bare `except:`. Catch the most specific exception. Use `logger.exception()` to include tracebacks. Define custom exception hierarchies for your application.

© rohitg00 · Apache-2.0 · rohitg00/awesome-claude-code-toolkit

Similar skills

All skills for Programming languages →

python-best-practices by other authors comes first.

python-best-practices python-best-practices python-best-practices — a skill with 75 Python rules drawn from real PR review patterns, covering dataclasses, service interfaces, error handling and type annotations. CX Codex +1 871installs python-best-practices c0x12c python-best-practices defines architectural and coding standards for FastAPI and Pydantic v2. Keeps async endpoints free from blocking calls and aligns layer boundaries. CX Codex +1 ★ 111repo stars python siviter-xyz Gives the agent one set of Python conventions: typing, dependency injection, module and test layout. Useful when edits land in an existing codebase. CX Codex +1 353installs python-pro davila7 python-pro — a Claude Code skill that puts the agent into expert mode for modern Python. It covers 3.12+ features, async work, profiling, and the current tooling stack. CX Codex +1 399installs ac-python souliane ac-python guides Python style, typing, OOP, testing, and tooling. Use it for scripts, CLIs, microservices, and data pipelines outside Django. CX Codex +1 1,000installs 102-python-patterns obviousworks 102-python-patterns defines modern Python conventions for AI coding: strict typing, async I/O, PEP 8 compliance, and structured error handling in **/*.py files. +1 ★ 97repo stars python-cybersecurity-tool-development Mindrally python-cybersecurity-tool-development is a Claude Code skill that teaches agents to build Python pentesting tools such as port scanners, enumerators, and brute-forcers, with async networking, input validation, and structured logs. CX Codex +1 1,000installs python-coder sno-ai The python-coder skill for Claude Code guides Python implementation and refactoring, including work with FastAPI and Pydantic. It applies to async code and migration tasks. CX Codex +1 ★ 869repo stars

From the same set178

The whole set →
devops-automation The devops-automation skill guides CI/CD design for GitHub Actions and configuration work with Docker, Kubernetes, Helm, and ArgoCD. Use it when planning an application build and deployment flow. CX Codex +1 ★ 2,858repo stars technology-scout technology-scout is a Claude Code subagent that evaluates emerging technologies, compares build-versus-buy options, and assesses vendors to inform adoption decisions. CX Codex ★ 2,858repo stars react-patterns react-patterns is a Claude Code skill with React 19 patterns for Server Components, Server Actions, Suspense, and state management. CX Codex +1 ★ 2,858repo stars data-engineering The data-engineering skill offers patterns for ETL pipelines, data warehouses, and Apache Spark jobs. Use it to shape data quality checks and warehouse schemas. CX Codex +1 ★ 2,858repo stars golang-idioms golang-idioms is a Claude Code skill that provides idiomatic Go guidance for error handling, concurrency, and testing. CX Codex +1 ★ 2,858repo stars workflow-optimizer The workflow-optimizer plugin analyzes development workflows and suggests ways to improve them. Use it when you want recommendations on how work in a project is organized. ★ 2,858repo stars web-dev web-dev — a plugin for Claude Code that automates full-stack web app creation: generates project structure, components, and pages in a single step. ★ 2,858repo stars visual-regression Runs visual regression testing via screenshot comparison in Claude Code. Pinpoints unwanted layout shifts right after styling changes. ★ 2,858repo stars

Project sponsors

Companies that keep this analytics open