mcpField
C
coding-standards

coding-standards

github.com/ludo-technologiesDevelopment3447 installsUpdated 2w ago
Repository

About coding-standards

A collection of Python coding standards for AI agents and LLMs. It organizes guidance on performance, async processing, design, documentation, validation, and object-oriented programming, with examples for common patterns.

Key features

  1. 01Error-handling rules
  2. 02Performance optimization patterns
  3. 03Async processing guidance
  4. 04Design and SOLID principles
  5. 05Documentation and type hints

Use cases

  1. 01Guide Python code generation
  2. 02Review Python implementation patterns
  3. 03Apply async resource-management practices
  4. 04Standardize public API documentation

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/ludo-technologies/python-best-practices --skill coding-standards

After installing, type/coding-standardsin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

metadata.json
README.md
rules/
_sections.md
_template.md
async-context-manager.md
async-create-task.md
async-gather.md
async-semaphore.md
design-dependency-injection.md
design-early-return.md
design-no-global-singleton.md
design-philosophy.md
design-pure-functions.md
design-single-responsibility.md
doc-docstring.md
doc-type-hints.md
error-no-silent-exceptions.md
oop-composition-over-inheritance.md
oop-dataclass.md
oop-property.md
oop-protocol.md
perf-dict-get.md
perf-generator-expression.md
perf-list-comprehension.md
perf-set-lookup.md
perf-str-join.md
solid-isp.md
solid-lsp.md
solid-ocp.md
validation-pydantic.md

Details

From the project README

Python Coding Standards

A comprehensive collection of Python coding standards and best practices. Designed for AI agents and LLMs to generate high-quality, performant, and maintainable Python code.

Categories

Error Handling [CRITICAL]

Prevent failures from being hidden or reported as successful outcomes.

RuleDescription
error-no-silent-exceptionsNever swallow exceptions
Performance Optimization [CRITICAL]

Apply Python optimization patterns to improve processing speed and memory efficiency.

RuleDescription
perf-list-comprehensionPrefer list comprehensions over loops (1.5-2x faster)
perf-generator-expressionUse generators for large datasets (O(1) memory)
perf-dict-getUse dict.get() for efficient default values
perf-set-lookupUse set for fast lookups (O(1) vs O(n))
perf-str-joinUse join for string concatenation (O(n) vs O(n²))
Async Processing [HIGH]

Efficient asynchronous programming patterns using asyncio.

RuleDescription
async-gatherUse asyncio.gather for independent tasks
async-create-taskProper background task creation
async-context-managerResource management with async with
async-semaphoreLimit concurrency with semaphores
Design Principles [HIGH]

Software design principles for maintainability and extensibility.

RuleDescription
design-philosophyDRY, YAGNI, KISS principles
design-single-responsibilitySingle Responsibility Principle
design-dependency-injectionLoose coupling with dependency injection
design-no-global-singletonAvoid global singletons and module-level shared instances
solid-ocpOpen/Closed Principle
solid-lspLiskov Substitution Principle
solid-ispInterface Segregation Principle
design-pure-functionsPrefer pure functions without side effects
design-early-returnReduce nesting with early returns
Documentation [HIGH]

Documentation standards for public API clarity and machine-checkable contracts.

RuleDescription
doc-docstringDocument public APIs with Google style docstrings
doc-type-hintsRequire type hints for public APIs
Data Validation [HIGH]

Validation patterns for data crossing trust boundaries.

RuleDescription
validation-pydanticUse Pydantic for boundary data validation
Object-Oriented Programming [MEDIUM]

Best practices for Pythonic object-oriented programming.

RuleDescription
oop-composition-over-inheritancePrefer composition over inheritance
oop-dataclassUse dataclass for data containers
oop-protocolPrefer Protocol over abstract base classes
oop-propertyUse property instead of getters

Quick Reference

Error Handling
try:
    config = parse_config(path)
except ConfigParseError as exc:
    raise StartupError(f"Invalid configuration: {path}") from exc


def main() -> int:
    try:
        start_application()
    except StartupError:
        logger.exception("Application startup failed")
        return 1  # explicit non-success outcome at the process boundary
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
Performance Patterns
# List comprehension (not loops)
result = [x * 2 for x in items]

# Generator for large data
total = sum(x * x for x in range(1_000_000))

# dict.get() with default
value = config.get("key", default_value)

# Set for fast lookup
valid_ids: set[int] = {1, 2, 3}
if item_id in valid_ids: ...

# join for strings
result = ",".join(values)
Async Patterns
# Concurrent execution
results = await asyncio.gather(task1(), task2(), task3())

# Resource management
async with aiohttp.ClientSession() as session:
    async with session.get(url) as response:
        data = await response.json()

# Concurrency limit
semaphore = asyncio.Semaphore(10)
async with semaphore:
    await do_work()
Design Patterns
# Dependency injection (not module-level singletons)
class Service:
    def __init__(self, repository: Repository) -> None:
        self.repository = repository

# Composition root builds the graph once
def create_app(settings: Settings) -> Service:
    return Service(repository=PostgresRepository(settings.dsn))

# Open/Closed: extend via new types, not edits
class JsonFormat:
    def export(self, invoice: Invoice) -> str: ...

# Interface Segregation: small Protocols
class Workable(Protocol):
    def work(self) -> None: ...

# Early return
def process(data: Data | None) -> Result:
    if data is None:
        return Result.empty()
    # main logic here
Documentation Patterns
def create_user(email: str, name: str) -> User:
    """Create a user account.

    Args:
        email: Unique email address for the account.
        name: Display name for the user.

    Returns:
        The created user.
    """
    return user_repository.create(email=email, name=name)
Validation Patterns
from pydantic import BaseModel, EmailStr, Field

class CreateUserRequest(BaseModel):
    email: EmailStr
    age: int = Field(ge=0, le=150)
OOP Patterns
# Dataclass
@dataclass
class User:
    name: str
    email: str

# Protocol for interfaces
class Repository(Protocol):
    def get(self, id: str) -> Entity: ...

# Property
@property
def full_name(self) -> str:
    return f"{self.first} {self.last}"

See Also

  • Recommended Tooling - Tools to enforce these standards automatically (ruff, mypy, pytest, pyscn, uv)

Comments

Markdown supported