PluginBench
Skill
Pass
Audit score 90

python-patterns

sickn33/agentic-awesome-skills

Python development principles and decision-making for architecture, frameworks, async patterns, and project structure.

What is python-patterns?

This skill teaches Python architectural thinking rather than rote pattern copying. Use it when making framework selection decisions, designing async vs sync code, implementing type hints, structuring projects, or choosing between tools like FastAPI, Django, and Flask based on context.

  • Framework selection decision tree for FastAPI, Django, Flask, and background task systems
  • Async vs sync decision guidance with I/O-bound and CPU-bound context rules
  • Type hints strategy covering when to type, Pydantic validation, and common patterns
  • Project structure templates for small scripts, medium APIs, and large applications
  • Django 5.0+ async support and best practices for models, views, and queries
  • FastAPI dependency injection, Pydantic v2 integration, and async endpoint patterns

How to install python-patterns

npx skills add https://github.com/sickn33/agentic-awesome-skills --skill python-patterns
Claude Code
Cursor
Windsurf
Cline

How to use python-patterns

  1. 1.Identify what you're building (API, full-stack, microservice, script, or background worker)
  2. 2.Use the framework selection decision tree to choose between FastAPI, Django, or Flask based on your requirements
  3. 3.Determine if your workload is I/O-bound (use async) or CPU-bound (use sync or multiprocessing)
  4. 4.Apply the appropriate project structure template based on project size and complexity
  5. 5.Implement type hints following the strategy: always type function parameters and return types, use Pydantic for API models
  6. 6.Select async libraries (httpx, asyncpg, aioredis) that match your I/O operations
  7. 7.Choose a background task solution based on complexity: BackgroundTasks for simple tasks, Celery/ARQ for distributed work
  8. 8.Write tests using pytest with async support where needed, following the fixture and integration testing patterns

Use cases

Good for
  • Deciding between FastAPI, Django, or Flask for a new API or web project
  • Choosing async vs sync patterns when building microservices or handling concurrent connections
  • Structuring a FastAPI project with proper separation of routes, services, models, and schemas
  • Implementing type hints and Pydantic validation in a new Python codebase
  • Setting up background task processing for long-running operations in a web application
Who it's for
  • Python backend developers making architecture decisions
  • Teams evaluating framework choices for new projects
  • Developers transitioning to async Python patterns
  • API and microservice architects
  • Full-stack developers building with Django or FastAPI

python-patterns FAQ

When should I use FastAPI vs Django?

Use FastAPI for API-first, microservices, and async-heavy workloads with modern Python. Use Django for full-stack applications, CMS, admin interfaces, and when you need batteries-included features. FastAPI is lighter and faster; Django is more opinionated and feature-rich.

Should I always use async in Python?

No. Use async only for I/O-bound operations (database, HTTP, file access) with many concurrent connections. Use sync for CPU-bound work, simple scripts, or when blocking libraries are required. Mixing sync and async carelessly causes problems.

Do I need to type hint everything?

Always type function parameters, return types, and public APIs. You can skip local variables (let inference work), one-off scripts, and most test code. Type hints improve code clarity and enable better IDE support and error detection.

What's the best project structure for a FastAPI app?

For medium APIs, organize by layer (routes/, services/, models/, schemas/) or by feature (users/, products/). Use src/myapp/ for larger applications. Keep business logic in services, API contracts in schemas, and database models separate.

When should I use Celery vs FastAPI BackgroundTasks?

Use FastAPI BackgroundTasks for quick, fire-and-forget operations in the same process. Use Celery or ARQ for long-running tasks, distributed workers, retry logic, and persistent queues across multiple machines.

Full instructions (SKILL.md)

Source of truth, from sickn33/agentic-awesome-skills.


name: python-patterns description: "Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying." risk: critical source: community date_added: "2026-02-27"

Python Patterns

Python development principles and decision-making for 2025. Learn to THINK, not memorize patterns.

When to Use

Use this skill when making Python architecture decisions, choosing frameworks, designing async patterns, or structuring Python projects.


⚠️ How to Use This Skill

This skill teaches decision-making principles, not fixed code to copy.

  • ASK user for framework preference when unclear
  • Choose async vs sync based on CONTEXT
  • Don't default to same framework every time

1. Framework Selection (2025)

Decision Tree

What are you building?
│
├── API-first / Microservices
│   └── FastAPI (async, modern, fast)
│
├── Full-stack web / CMS / Admin
│   └── Django (batteries-included)
│
├── Simple / Script / Learning
│   └── Flask (minimal, flexible)
│
├── AI/ML API serving
│   └── FastAPI (Pydantic, async, uvicorn)
│
└── Background workers
    └── Celery + any framework

Comparison Principles

FactorFastAPIDjangoFlask
Best forAPIs, microservicesFull-stack, CMSSimple, learning
AsyncNativeDjango 5.0+Via extensions
AdminManualBuilt-inVia extensions
ORMChoose your ownDjango ORMChoose your own
Learning curveLowMediumLow

Selection Questions to Ask:

  1. Is this API-only or full-stack?
  2. Need admin interface?
  3. Team familiar with async?
  4. Existing infrastructure?

2. Async vs Sync Decision

When to Use Async

async def is better when:
├── I/O-bound operations (database, HTTP, file)
├── Many concurrent connections
├── Real-time features
├── Microservices communication
└── FastAPI/Starlette/Django ASGI

def (sync) is better when:
├── CPU-bound operations
├── Simple scripts
├── Legacy codebase
├── Team unfamiliar with async
└── Blocking libraries (no async version)

The Golden Rule

I/O-bound → async (waiting for external)
CPU-bound → sync + multiprocessing (computing)

Don't:
├── Mix sync and async carelessly
├── Use sync libraries in async code
└── Force async for CPU work

Async Library Selection

NeedAsync Library
HTTP clienthttpx
PostgreSQLasyncpg
Redisaioredis / redis-py async
File I/Oaiofiles
Database ORMSQLAlchemy 2.0 async, Tortoise

3. Type Hints Strategy

When to Type

Always type:
├── Function parameters
├── Return types
├── Class attributes
├── Public APIs

Can skip:
├── Local variables (let inference work)
├── One-off scripts
├── Tests (usually)

Common Type Patterns

# These are patterns, understand them:

# Optional → might be None
from typing import Optional
def find_user(id: int) -> Optional[User]: ...

# Union → one of multiple types
def process(data: str | dict) -> None: ...

# Generic collections
def get_items() -> list[Item]: ...
def get_mapping() -> dict[str, int]: ...

# Callable
from typing import Callable
def apply(fn: Callable[[int], str]) -> str: ...

Pydantic for Validation

When to use Pydantic:
├── API request/response models
├── Configuration/settings
├── Data validation
├── Serialization

Benefits:
├── Runtime validation
├── Auto-generated JSON schema
├── Works with FastAPI natively
└── Clear error messages

4. Project Structure Principles

Structure Selection

Small project / Script:
├── main.py
├── utils.py
└── requirements.txt

Medium API:
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models/
│   ├── routes/
│   ├── services/
│   └── schemas/
├── tests/
└── pyproject.toml

Large application:
├── src/
│   └── myapp/
│       ├── core/
│       ├── api/
│       ├── services/
│       ├── models/
│       └── ...
├── tests/
└── pyproject.toml

FastAPI Structure Principles

Organize by feature or layer:

By layer:
├── routes/ (API endpoints)
├── services/ (business logic)
├── models/ (database models)
├── schemas/ (Pydantic models)
└── dependencies/ (shared deps)

By feature:
├── users/
│   ├── routes.py
│   ├── service.py
│   └── schemas.py
└── products/
    └── ...

5. Django Principles (2025)

Django Async (Django 5.0+)

Django supports async:
├── Async views
├── Async middleware
├── Async ORM (limited)
└── ASGI deployment

When to use async in Django:
├── External API calls
├── WebSocket (Channels)
├── High-concurrency views
└── Background task triggering

Django Best Practices

Model design:
├── Fat models, thin views
├── Use managers for common queries
├── Abstract base classes for shared fields

Views:
├── Class-based for complex CRUD
├── Function-based for simple endpoints
├── Use viewsets with DRF

Queries:
├── select_related() for FKs
├── prefetch_related() for M2M
├── Avoid N+1 queries
└── Use .only() for specific fields

6. FastAPI Principles

async def vs def in FastAPI

Use async def when:
├── Using async database drivers
├── Making async HTTP calls
├── I/O-bound operations
└── Want to handle concurrency

Use def when:
├── Blocking operations
├── Sync database drivers
├── CPU-bound work
└── FastAPI runs in threadpool automatically

Dependency Injection

Use dependencies for:
├── Database sessions
├── Current user / Auth
├── Configuration
├── Shared resources

Benefits:
├── Testability (mock dependencies)
├── Clean separation
├── Automatic cleanup (yield)

Pydantic v2 Integration

# FastAPI + Pydantic are tightly integrated:

# Request validation
@app.post("/users")
async def create(user: UserCreate) -> UserResponse:
    # user is already validated
    ...

# Response serialization
# Return type becomes response schema

7. Background Tasks

Selection Guide

SolutionBest For
BackgroundTasksSimple, in-process tasks
CeleryDistributed, complex workflows
ARQAsync, Redis-based
RQSimple Redis queue
DramatiqActor-based, simpler than Celery

When to Use Each

FastAPI BackgroundTasks:
├── Quick operations
├── No persistence needed
├── Fire-and-forget
└── Same process

Celery/ARQ:
├── Long-running tasks
├── Need retry logic
├── Distributed workers
├── Persistent queue
└── Complex workflows

8. Error Handling Principles

Exception Strategy

In FastAPI:
├── Create custom exception classes
├── Register exception handlers
├── Return consistent error format
└── Log without exposing internals

Pattern:
├── Raise domain exceptions in services
├── Catch and transform in handlers
└── Client gets clean error response

Error Response Philosophy

Include:
├── Error code (programmatic)
├── Message (human readable)
├── Details (field-level when applicable)
└── NOT stack traces (security)

9. Testing Principles

Testing Strategy

TypePurposeTools
UnitBusiness logicpytest
IntegrationAPI endpointspytest + httpx/TestClient
E2EFull workflowspytest + DB

Async Testing

# Use pytest-asyncio for async tests

import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.get("/users")
        assert response.status_code == 200

Fixtures Strategy

Common fixtures:
├── db_session → Database connection
├── client → Test client
├── authenticated_user → User with token
└── sample_data → Test data setup

10. Decision Checklist

Before implementing:

  • Asked user about framework preference?
  • Chosen framework for THIS context? (not just default)
  • Decided async vs sync?
  • Planned type hint strategy?
  • Defined project structure?
  • Planned error handling?
  • Considered background tasks?

11. Anti-Patterns to Avoid

❌ DON'T:

  • Default to Django for simple APIs (FastAPI may be better)
  • Use sync libraries in async code
  • Skip type hints for public APIs
  • Put business logic in routes/views
  • Ignore N+1 queries
  • Mix async and sync carelessly

✅ DO:

  • Choose framework based on context
  • Ask about async requirements
  • Use Pydantic for validation
  • Separate concerns (routes → services → repos)
  • Test critical paths

Remember: Python patterns are about decision-making for YOUR specific context. Don't copy code—think about what serves your application best.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.