python-patterns
414
总安装量
414
周安装量
#660
全站排名
安装命令
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill python-patterns
Agent 安装分布
opencode
276
claude-code
275
gemini-cli
233
codex
199
cursor
187
Skill 文档
Python Patterns
Python development principles and decision-making for 2025. Learn to THINK, not memorize patterns.
â ï¸ 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
| Factor | FastAPI | Django | Flask |
|---|---|---|---|
| Best for | APIs, microservices | Full-stack, CMS | Simple, learning |
| Async | Native | Django 5.0+ | Via extensions |
| Admin | Manual | Built-in | Via extensions |
| ORM | Choose your own | Django ORM | Choose your own |
| Learning curve | Low | Medium | Low |
Selection Questions to Ask:
- Is this API-only or full-stack?
- Need admin interface?
- Team familiar with async?
- 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
| Need | Async Library |
|---|---|
| HTTP client | httpx |
| PostgreSQL | asyncpg |
| Redis | aioredis / redis-py async |
| File I/O | aiofiles |
| Database ORM | SQLAlchemy 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
| Solution | Best For |
|---|---|
| BackgroundTasks | Simple, in-process tasks |
| Celery | Distributed, complex workflows |
| ARQ | Async, Redis-based |
| RQ | Simple Redis queue |
| Dramatiq | Actor-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
| Type | Purpose | Tools |
|---|---|---|
| Unit | Business logic | pytest |
| Integration | API endpoints | pytest + httpx/TestClient |
| E2E | Full workflows | pytest + 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.