This skill teaches Python decision-making principles for 2025, not fixed code patterns to copy. Learn to THINK about framework selection and architecture based on context.
What This Skill Provides
The Python Patterns skill provides comprehensive Python development principles covering FastAPI, Django 5.0+, async programming, type hints, project structure, and testing.Core Knowledge Areas
Framework Selection
Decision trees for FastAPI (async APIs), Django (full-stack), Flask (simple)
Async vs Sync
When to use async/await, async library selection, avoiding common pitfalls
Type Hints
When to type, Pydantic for validation, generic patterns
Project Structure
Small, medium, and large project organization patterns
Background Tasks
Celery, ARQ, RQ, Dramatiq, BackgroundTasks selection
Testing
pytest, async testing, fixtures strategy
When This Skill Is Loaded
Agents load this skill when:- Building Python APIs or web applications
- Choosing between FastAPI, Django, or Flask
- Implementing async patterns in Python
- Working with Pydantic for validation
- Structuring Python projects
- Setting up background task processing
- Writing Python tests
- Optimizing Python backend performance
Use Cases
Framework Selection (2025)
Decision tree based on project requirements:Framework Comparison
| 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 |
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
- 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 resources)
CPU-bound → sync + multiprocessing (computing)Don’t:
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 |
Key Principles
Type Hints Strategy
When to Type
Always type:
- Function parameters
- Return types
- Class attributes
- Public APIs
- Local variables (inference works)
- One-off scripts
- Tests (usually)
Common Type Patterns
Pydantic for Validation
Use Pydantic For
- API request/response models
- Configuration/settings
- Data validation
- Serialization
Benefits
- Runtime validation
- Auto JSON schema generation
- Native FastAPI integration
- Clear error messages
Project Structure
Structure Selection
FastAPI Structure Principles
By Layer
- routes/ (API endpoints)
- services/ (business logic)
- models/ (database models)
- schemas/ (Pydantic models)
- dependencies/ (shared deps)
By Feature
- users/ (all user-related)
- products/ (all product-related)
- Each with routes, service, schemas
Django Best Practices (2025)
Django Async Support (5.0+)
Django 5.0+ supports:
- Async views
- Async middleware
- Async ORM (limited)
- ASGI deployment
- External API calls
- WebSocket (Channels)
- High-concurrency views
- Background task triggering
Django Optimization
Query Optimization:select_related()for foreign keysprefetch_related()for many-to-many- Avoid N+1 queries
- Use
.only()for specific fields
- Class-based for complex CRUD
- Function-based for simple endpoints
- Viewsets with Django REST Framework
FastAPI Principles
async def vs def in FastAPI
Choose Based on Operations
Use async def when:
- Using async database drivers
- Making async HTTP calls
- I/O-bound operations
- Want to handle concurrency
- 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
- Testability (mock dependencies)
- Clean separation
- Automatic cleanup (yield pattern)
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 |
FastAPI BackgroundTasks
Use for:
- Quick operations
- No persistence needed
- Fire-and-forget
- Same process
Celery/ARQ
Use for:
- Long-running tasks
- Need retry logic
- Distributed workers
- Persistent queue
- Complex workflows
Related Skills
API Patterns
API design principles for REST and GraphQL
Node.js Best Practices
Alternative backend runtime patterns
Rust Pro
High-performance systems programming
Which Agents Use This Skill
Backend Specialist
The Backend Specialist loads this skill for all Python backend development. It’s used alongside
api-patterns for API design and other backend skills.Testing Strategy
| Type | Purpose | Tools |
|---|---|---|
| Unit | Business logic | pytest |
| Integration | API endpoints | pytest + httpx/TestClient |
| E2E | Full workflows | pytest + DB |
Async Testing
Fixtures Strategy
Common fixtures:db_session→ Database connectionclient→ Test clientauthenticated_user→ User with tokensample_data→ Test data setup
Anti-Patterns to Avoid
Decision Checklist
Before implementing:
- Asked user about framework preference?
- Chosen framework for THIS context? (not default)
- Decided async vs sync?
- Planned type hint strategy?
- Defined project structure?
- Planned error handling?
- Considered background tasks?
Error Handling
Exception Strategy
In FastAPI:- Create custom exception classes
- Register exception handlers
- Return consistent error format
- Log without exposing internals
- Include error code (programmatic)
- Message (human readable)
- Details (field-level when applicable)
- NOT stack traces (security)
