agentleFS
I-OnlabsI-Onlabs/claude-code-skills/python-best-practices/SKILL.md

python-best-practices

Skill4 starsChanged 26 days agoMITView on GitHub

Use when writing Python code. Enforces modern Python 3.11+ patterns, comprehensive type hints, async patterns, and production-ready code quality standards.

19 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use react-best-practices, typescript-best-practices and 1 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • OpenAISkill

    react-best-practices

    React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

    Also in 3 projects that use this

  • jaydubya818Skill

    typescript-best-practices

    Use when TypeScript needs focused type-safety, API, or error-handling guidance.

    Also in 3 projects that use this

  • GoogleSkill

    tdd

    Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.

    Also in 3 projects that use this

The file

Files
SKILL.md

Python Best Practices

When This Skill Activates

  • Writing any Python code
  • Reviewing Python code
  • Setting up Python projects
  • Questions about Python patterns

Modern Python Patterns (3.11+)

Type Hints Everywhere

# Modern union syntax (3.10+)
def process(value: str | None) -> dict[str, int]:
    ...

# NOT the old way
from typing import Optional, Dict
def process(value: Optional[str]) -> Dict[str, int]:  # Don't do this
    ...

Match Statements (3.10+)

# Modern pattern matching
match response.status_code:
    case 200:
        return response.json()
    case 404:
        raise NotFoundError()
    case 500:
        raise ServerError()
    case _:
        raise UnexpectedError(response.status_code)

# NOT if/elif chains for this
if response.status_code == 200:  # Don't do this for case analysis
    ...

Data Classes & Pydantic

# For simple data containers
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

# For validation & serialization
from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str
    age: int = 0

Async Patterns

Use async for I/O

# Good - async for I/O operations
async def fetch_data(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# Bad - sync in async context
def fetch_data(url: str) -> dict:  # Blocks event loop
    return requests.get(url).json()

Concurrent Operations

# Run multiple async operations concurrently
async def fetch_all(urls: list[str]) -> list[dict]:
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_one(session, url) for url in urls]
        return await asyncio.gather(*tasks)

Context Managers

# Async context managers for resources
async with aiofiles.open("file.txt") as f:
    content = await f.read()

# Async generators
async def stream_data():
    async for chunk in response.content:
        yield process(chunk)

Code Quality Tools

Type Checking

# Use mypy or pyright
mypy src/ --strict
pyright src/

Linting

# Use ruff (fast, comprehensive)
ruff check .
ruff format .

# Or black + isort + flake8
black .
isort .
flake8 .

Pre-commit Config

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.0.0
    hooks:
      - id: mypy

Project Structure

project/
├── src/
│   └── mypackage/
│       ├── __init__.py
│       ├── models.py
│       ├── services.py
│       └── api/
│           ├── __init__.py
│           └── routes.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   └── test_services.py
├── pyproject.toml
├── README.md
└── .pre-commit-config.yaml

Testing with Pytest

import pytest
from unittest.mock import AsyncMock

# Fixtures
@pytest.fixture
def user_service():
    return UserService(db=MockDB())

# Async tests
@pytest.mark.asyncio
async def test_create_user(user_service):
    user = await user_service.create(UserCreate(name="Test"))
    assert user.name == "Test"

# Parametrized tests
@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
])
def test_uppercase(input, expected):
    assert input.upper() == expected

# Mocking
async def test_external_api(mocker):
    mock_fetch = mocker.patch("module.fetch", new_callable=AsyncMock)
    mock_fetch.return_value = {"data": "test"}
    result = await process_data()
    assert result == {"data": "test"}

Dependency Management

# pyproject.toml
[project]
name = "mypackage"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "fastapi>=0.100.0",
    "pydantic>=2.0.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0.0",
    "pytest-asyncio>=0.21.0",
    "ruff>=0.1.0",
    "mypy>=1.0.0",
]

Common Anti-Patterns

Don'tDo
from typing import Optionalstr | None
Dict[str, Any]dict[str, Any]
Bare except:except Exception:
== Noneis None
Mutable default argsfield(default_factory=list)

Docstrings

def calculate_total(
    items: list[Item],
    discount: float = 0.0,
) -> float:
    """Calculate the total price with optional discount.

    Args:
        items: List of items to sum.
        discount: Percentage discount (0.0 to 1.0).

    Returns:
        Total price after discount.

    Raises:
        ValueError: If discount is not between 0 and 1.
    """
    ...

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.