Implement GitOps workflows with ArgoCD and Flux for automated, declarative Kubernetes...
npx skills add halay08/fullstack-agent-skills --skill "python-patterns"
Install specific skill from multi-skill repository
# Description
Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
# SKILL.md
name: python-patterns
description: Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
allowed-tools: Read, Write, Edit, Glob, Grep
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.
# Supported AI Coding Agents
This skill is compatible with the SKILL.md standard and works with all major AI coding agents:
Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.