Python rules

From Luohaothu/everything-codex · View interactive version

Python rules is an AI agent skill from the GitHub repository Luohaothu/everything-codex. Comprehensive Python coding rules covering style, patterns, testing, and security

How to use this skill

Skill file

Python Coding Rules

Coding Style

Immutability (CRITICAL)

ALWAYS create new objects, NEVER mutate existing ones:

// Pseudocode
WRONG:  modify(original, field, value) -> changes original in-place
CORRECT: update(original, field, value) -> returns new copy with change

Rationale: Immutable data prevents hidden side effects, makes debugging easier, and enables safe concurrency.

File Organization

MANY SMALL FILES > FEW LARGE FILES:

Standards

Immutable Data Structures

Prefer immutable data structures:

from dataclasses import dataclass

@dataclass(frozen=True)
class User:
    name: str
    email: str

from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float

Formatting

Error Handling

ALWAYS handle errors comprehensively:

Input Validation

ALWAYS validate at system boundaries:

Code Quality Checklist

Before marking work complete:

Patterns

Skeleton Projects

When implementing new functionality:

  1. Search for battle-tested skeleton projects
  2. Evaluate options for security, extensibility, relevance
  3. Clone best match as foundation
  4. Iterate within proven structure

Repository Pattern

Encapsulate data access behind a consistent interface:

API Response Format

Use a consistent envelope for all API responses:

Protocol (Duck Typing)

from typing import Protocol

class Repository(Protocol):
    def find_by_id(self, id: str) -> dict | None: ...
    def save(self, entity: dict) -> dict: ...

Dataclasses as DTOs

from dataclasses import dataclass

@dataclass
class CreateUserRequest:
    name: str
    email: str
    age: int | None = None

Context Managers & Generators

Testing

Minimum Test Coverage: 80%

Test Types (ALL required):

  1. Unit Tests - Individual functions, utilities, components
  2. Integration Tests - API endpoints, database operations
  3. E2E Tests - Critical user flows

Test-Driven Development

MANDATORY workflow:

  1. Write test first (RED)
  2. Run test - it should FAIL
  3. Write minimal implementation (GREEN)
  4. Run test - it should PASS
  5. Refactor (IMPROVE)
  6. Verify coverage (80%+)

Troubleshooting Test Failures

  1. Check test isolation
  2. Verify mocks are correct
  3. Fix implementation, not tests (unless tests are wrong)

Framework

Use pytest as the testing framework.

Coverage

pytest --cov=src --cov-report=term-missing

Test Organization

Use pytest.mark for test categorization:

import pytest

@pytest.mark.unit
def test_calculate_total():
    ...

@pytest.mark.integration
def test_database_connection():
    ...

Security

Mandatory Security Checks

Before ANY commit:

Secret Management

import os
from dotenv import load_dotenv

load_dotenv()

api_key = os.environ["OPENAI_API_KEY"]  # Raises KeyError if missing

Security Scanning

```bash

bandit -r src/

```

Security Response Protocol

If security issue found:

  1. STOP immediately
  2. Fix CRITICAL issues before continuing
  3. Rotate any exposed secrets
  4. Review entire codebase for similar issues
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.