agentleFS
b33eepb33eep/claude-code-setup/skills/standards-python/SKILL.md

standards-python

Skill57 starsChanged 10 months agoMITView on GitHub

This skill provides Python coding standards and is automatically loaded for Python projects. It includes naming conventions, best practices, and recommended tooling.

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

9 rules. About 0 are common, 6 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈6

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    DRY: Don't Repeat Yourself - but don't overdo it

    line 17
  2. Distinctive:

    Early Returns: Use early returns to avoid nesting

    line 21
  3. Distinctive:

    Minimal Changes: Only change relevant code parts

    line 23
  4. Distinctive:

    No Over-Engineering: No unnecessary complexity

    line 24
  5. Distinctive:

    Pydantic for validation: - Don't validate manually, use Pydantic models

    line 182
  6. Distinctive:

    Async for I/O: - Use async/await for network, database, file operations

    line 183
  7. Very specific:

    No blocking in async: - Never use time.sleep() or sync I/O in async functions

    line 184
  8. Very specific:

    Structured logging: - Use logging module with JSON format, not print()

    line 185
  9. Very specific:

    Environment variables: - Use pydantic-settings for config, never hardcode secrets

    line 186

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python Coding Standards

Core Principles

  1. Simplicity: Simple, understandable code
  2. Readability: Readability over cleverness
  3. Maintainability: Code that's easy to maintain
  4. Testability: Code that's easy to test
  5. DRY: Don't Repeat Yourself - but don't overdo it

General Rules

  • Early Returns: Use early returns to avoid nesting
  • Descriptive Names: Meaningful names for variables and functions
  • Minimal Changes: Only change relevant code parts
  • No Over-Engineering: No unnecessary complexity
  • Minimal Comments: Code should be self-explanatory. No redundant comments!

Naming Conventions

ElementConventionExample
Variables/Functionssnake_caseget_user_by_id, is_active
ClassesPascalCaseUserService, ApiClient
ConstantsUPPER_SNAKE_CASEMAX_RETRY_COUNT
PrivatePrefix with __internal_method
Files/Modulessnake_caseuser_service.py

Project Structure

myproject/
├── src/
│   ├── __init__.py
│   ├── main.py              # Entry point
│   ├── config.py            # Settings, env vars
│   ├── models.py            # Domain models (dataclasses/Pydantic)
│   ├── schemas.py           # Request/response DTOs
│   ├── services/
│   │   ├── __init__.py
│   │   └── user_service.py  # Business logic
│   └── repositories/
│       ├── __init__.py
│       └── user_repo.py     # Data access
├── tests/
│   ├── __init__.py
│   ├── test_services.py
│   └── test_repositories.py
├── pyproject.toml
└── README.md

Code Style (PEP 8 + PEP 484)

from dataclasses import dataclass

@dataclass
class User:
    id: str
    name: str
    email: str
    age: int | None = None  # Python 3.10+ union syntax

def get_user_by_id(user_id: str) -> User | None:
    if not user_id:
        raise ValueError("user_id cannot be empty")
    # implementation...

Best Practices

# Type hints everywhere
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Pydantic v2 for validation
from pydantic import BaseModel, Field, field_validator, EmailStr

class UserCreate(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    email: EmailStr
    age: int | None = Field(None, ge=0, le=150)

    @field_validator('name')
    @classmethod
    def name_must_be_alphanumeric(cls, v: str) -> str:
        if not v.replace(' ', '').isalnum():
            raise ValueError('Name must be alphanumeric')
        return v.strip()

# Context managers
with open('file.txt', 'r') as f:
    content = f.read()

# Prefer pathlib over os.path
from pathlib import Path
config_path = Path(__file__).parent / 'config.yaml'

Async/Await

# Async function with proper typing
async def fetch_user(user_id: str) -> User | None:
    async with httpx.AsyncClient() as client:
        response = await client.get(f"/users/{user_id}")
        return User(**response.json()) if response.status_code == 200 else None

# Don't block async functions
async def process_data():
    # BAD - blocks the event loop
    time.sleep(1)

    # GOOD - async sleep
    await asyncio.sleep(1)

# Gather for concurrent operations
async def fetch_all_users(user_ids: list[str]) -> list[User]:
    tasks = [fetch_user(uid) for uid in user_ids]
    return await asyncio.gather(*tasks)

Exception Handling

# Custom exceptions for domain errors
class UserNotFoundError(Exception):
    def __init__(self, user_id: str):
        self.user_id = user_id
        super().__init__(f"User not found: {user_id}")

# Raise vs Return None
def get_user_strict(user_id: str) -> User:
    """Raises if not found - use when user MUST exist."""
    user = repository.get(user_id)
    if not user:
        raise UserNotFoundError(user_id)
    return user

def get_user_optional(user_id: str) -> User | None:
    """Returns None if not found - use when absence is expected."""
    return repository.get(user_id)

Comments - Less is More

# BAD - redundant comment
# Get the user from database
user = repository.get_user(user_id)

# GOOD - self-explanatory code, no comment needed
user = repository.get_user(user_id)

# GOOD - comment explains WHY (not obvious)
# Rate limit: Azure API allows max 1000 requests/min
await rate_limiter.acquire()

Recommended Tooling

ToolPurpose
uvPackage manager (faster than pip/poetry)
ruffLinting (replaces flake8, isort, black)
mypy or pyrightType checking
pytestTesting with pytest-cov, pytest-asyncio

Production Best Practices

  1. Type hints everywhere - Parameters, return types, variables where helpful
  2. Pydantic for validation - Don't validate manually, use Pydantic models
  3. Async for I/O - Use async/await for network, database, file operations
  4. No blocking in async - Never use time.sleep() or sync I/O in async functions
  5. Structured logging - Use logging module with JSON format, not print()
  6. Environment variables - Use pydantic-settings for config, never hardcode secrets
  7. Dependency injection - Pass dependencies explicitly, makes testing easier
  8. Custom exceptions - Domain-specific errors, not generic Exception
  9. Connection pooling - Reuse database/HTTP connections, don't create per request
  10. Graceful shutdown - Handle SIGTERM, close connections properly

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.