agentleFS
komlukkomluk/scaffolding/skills/python-patterns/SKILL.md

python-patterns

Skill16 starsChanged 4 days agoMITView on GitHub

Python backend patterns: layered architecture, async I/O, dependency injection, repository/service separation. TRIGGER when: creating routes, models, schemas, or services in a Python backend. SKIP: REST contract design (use api-design); schema/index tuning (use database-optimization). (Examples: FastAPI + SQLAlchemy + Pydantic.)

  • Reads credentials

56 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use configure-ecc, nuxt4-patterns and 10 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.
  • royaluniondesign-sysSkill

    configure-ecc

    Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.

    Also in 12 projects that use this

  • loulanyueSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 10 projects that use this

  • RojiosSkill

    dart-flutter-patterns

    Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.

    Also in 7 projects that use this

  • royaluniondesign-sysSkill

    content-hash-cache-pattern

    Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.

    Also in 16 projects that use this

  • TironFoxSkill

    agent-payment-x402

    Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.

    Also in 6 projects that use this

  • TironFoxSkill

    openclaw-persona-forge

    为 OpenClaw AI Agent 锻造完整的龙虾灵魂方案。根据用户偏好或随机抽卡, 输出身份定位、灵魂描述(SOUL.md)、角色化底线规则、名字和头像生图提示词。 如当前环境提供已审核的生图 skill,可自动生成统一风格头像图片。 当用户需要创建、设计或定制 OpenClaw 龙虾灵魂时使用。 不适用于:微调已有 SOUL.md、非 OpenClaw 平台的角色设计、纯工具型无性格 Agent。 触发词:龙虾灵魂、虾魂、OpenClaw 灵魂、养虾灵魂、龙虾角色、龙虾定位、 龙虾剧本杀角色、龙虾游戏角色、龙虾 NPC、龙虾性格、龙虾背景故事、 lobster soul、lobster character、抽卡、随机龙虾、龙虾 SOUL、gacha。

    Also in 5 projects that use this

  • +1 more from royaluniondesign-sys

The file

Show its rules and text

We split this skill into the rules it gives an agent

20 rules. 0 are common, 8 are distinctive, and 12 are very specific to this project.

  • 0

    Common

    Most of the 53 edited versions we read keep these.

  • 8

    Distinctive

    This author's own choices. Worth a look.

  • 12

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use async_sessionmaker for async sessions

    line 65
  2. Distinctive:

    Use dependency injection for session

    line 66
  3. Distinctive:

    Commit in dependency, rollback on exception

    line 67
  4. Very specific:

    Use expire_on_commit=False for response data

    line 68
  5. Very specific:

    Use select() statements (SQLAlchemy 2.0 style)

    line 71
  6. Very specific:

    Prefer scalar_one_or_none() for single items

    line 72
  7. Very specific:

    Use scalars().all() for lists

    line 73
  8. Very specific:

    Use model_config = ConfigDict(from_attributes=True) for ORM

    line 90
  9. Very specific:

    Use Field() for validation constraints

    line 91
  10. Very specific:

    Use field_validator for custom validation

    line 92
  11. Very specific:

    Use pydantic-settings for env loading

    line 151
  12. Very specific:

    Use @lru_cache for singleton

    line 152
  13. Very specific:

    Use @property for computed values

    line 154
  14. Very specific:

    Use pytest.mark.asyncio for async tests

    line 173
  15. Distinctive:

    Use async/await consistently

    line 182
  16. Distinctive:

    Use type hints everywhere

    line 183
  17. Distinctive:

    Use Pydantic for all validation

    line 184
  18. Distinctive:

    Use repository pattern for data access

    line 186
  19. Distinctive:

    Put business logic in routes

    line 191
  20. Distinctive:

    Use raw SQL without parameters

    line 192

“Common” is measured: kept by at least 6 in 10 of the 53 edited versions of this file we could read. “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 Backend Patterns Skill

Purpose

Best practices for Python backend development: layered architecture, async I/O, dependency injection, and clear separation between HTTP handling, business logic, and data access. The concrete examples below use FastAPI, SQLAlchemy, and Pydantic, but the patterns apply to any Python web framework, ORM, and validation library.

Auto-Invoke Triggers

  • Creating backend routes / endpoints
  • Working with ORM models
  • Implementing async operations
  • Creating request/response validation schemas

Layer Responsibilities

LayerResponsibility
EndpointsHTTP handling, request/response
ServicesBusiness logic, orchestration
RepositoriesData access, queries
ModelsDatabase schema
SchemasData validation, serialization

These layers are framework-agnostic — keep HTTP concerns, business rules, and data access in separate modules regardless of which framework/ORM you use.


Example: FastAPI + SQLAlchemy + Pydantic (illustrative)

Illustrative — this is one concrete stack shown as an example. Substitute your framework's equivalents (any ASGI/WSGI framework, ORM, and validation library). The layering and separation-of-concerns patterns above are the reusable part.

Project Structure

app/
└── backend/
    ├── app/
    │   ├── main.py              # FastAPI app initialization
    │   ├── config.py            # Settings (pydantic-settings)
    │   ├── api/v1/endpoints/    # Route handlers
    │   ├── core/                # Security, exceptions
    │   ├── models/              # SQLAlchemy models
    │   ├── schemas/             # Pydantic schemas
    │   ├── services/            # Business logic
    │   ├── repositories/        # Data access
    │   └── db/session.py        # Database session
    ├── tests/
    ├── alembic.ini
    └── requirements.txt

Async Database Patterns

Session Management

  • Use async_sessionmaker for async sessions
  • Use dependency injection for session
  • Commit in dependency, rollback on exception
  • Use expire_on_commit=False for response data

Query Patterns

  • Use select() statements (SQLAlchemy 2.0 style)
  • Prefer scalar_one_or_none() for single items
  • Use scalars().all() for lists
  • Eager load relationships with selectin or joinedload

Pydantic Schema Patterns

Schema Types

TypePurposeExample
BaseShared fieldsUserBase(email, username)
CreatePOST requestUserCreate(Base + password)
UpdatePATCH requestUserUpdate(all optional)
ResponseAPI responseUserResponse(Base + id, created_at)
InDBInternal with secretsUserInDB(Response + hashed_password)

Best Practices

  • Use model_config = ConfigDict(from_attributes=True) for ORM
  • Use Field() for validation constraints
  • Use field_validator for custom validation
  • Separate request and response schemas

Repository Pattern

Base Repository Methods

  • get_by_id(id) - Single item by primary key
  • get_all(skip, limit) - Paginated list
  • create(**kwargs) - Insert new record
  • update(id, **kwargs) - Update existing
  • delete(id) - Remove record

Specific Repositories

  • Extend base with domain-specific queries
  • Example: get_by_email(), get_active_users()

Service Layer

Responsibilities

  • Validate business rules
  • Coordinate multiple repositories
  • Transform data between layers
  • Raise domain exceptions

Pattern

  • Inject repository via constructor
  • Return Pydantic schemas, not models
  • Raise specific exceptions (NotFoundError, ConflictError)

Dependency Injection

Common Dependencies

  • get_db - Database session
  • get_current_user - Authenticated user
  • get_current_superuser - Admin user
  • Service factories - get_user_service(session)

Pattern

# Endpoint receives dependencies, passes to service
async def create_user(
    data: UserCreate,
    session: AsyncSession = Depends(get_db)
):
    service = UserService(session)
    return await service.create(data)

Configuration

Settings Class

  • Use pydantic-settings for env loading
  • Use @lru_cache for singleton
  • Define defaults for optional settings
  • Use @property for computed values

Environment Variables

  • DATABASE_URL - Database connection
  • SECRET_KEY - JWT signing
  • DEBUG - Development mode
  • CORS_ORIGINS - Allowed origins

Testing Patterns

Fixtures

  • db_session - In-memory SQLite session
  • client - AsyncClient with app
  • Override get_db dependency for tests

Test Structure

  • One test file per module
  • Use pytest.mark.asyncio for async tests
  • AAA pattern: Arrange, Act, Assert
  • Mock external services

Best Practices

DO

  • Use async/await consistently
  • Use type hints everywhere
  • Use Pydantic for all validation
  • Use dependency injection
  • Use repository pattern for data access
  • Separate business logic into services

DON'T

  • Mix sync and async database calls
  • Put business logic in routes
  • Use raw SQL without parameters
  • Catch generic Exception
  • Store secrets in code
  • Skip server-side validation

Code Quality

ToolPurpose
blackCode formatting
ruffLinting
mypyType checking
pytestTesting
pytest-covCoverage

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.