python-patterns
Skill130 starsChanged 10 months agoMITView on GitHub
Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
We split this skill into the rules it gives an agent
7 rules. 0 are common, 7 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 43 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 18
ASK user for framework preference when unclear
- Distinctive: line 20
Don't default to same framework every time
- Distinctive: line 425
Default to Django for simple APIs (FastAPI may be better)
- Distinctive: line 426
Use sync libraries in async code
- Distinctive: line 428
Put business logic in routes/views
- Distinctive: line 434
Ask about async requirements
- Distinctive: line 435
Use Pydantic for validation
“Common” is measured: kept by at least 6 in 10 of the 43 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.
Files
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 frameworkComparison 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 workAsync 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 messages4. 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.tomlFastAPI 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 triggeringDjango 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 fields6. 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 automaticallyDependency 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 schema7. 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 workflows8. 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 responseError 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 == 200Fixtures Strategy
Common fixtures:
├── db_session → Database connection
├── client → Test client
├── authenticated_user → User with token
└── sample_data → Test data setup10. 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.
Other versions51 projects use a version of this.
Word for word · 6
- VoDaiLocz/kilo-kit-mcp★ 26100% same
- xfstudio/skills★ 9100% same
- SKB3002/agenthub★ 4100% same
- ai4brands-design/claude-skills★ 2100% same
- sid-lakhani/agents-config★ 2100% same
- MortuisVMain/ai-agent-superpowers★ 0100% same
Edited · 5
- vudovn/ag-kit★ 8.2k95% same
- vudovn/antigravity-kit★ 8.2k95% same
- kumaran-is/claude-code-onboarding★ 3537% same
- jornalistainclusivo/jinc-skills★ 192% same
- TheHiddenDeveloper/jarvis-skills★ 092% same
Wrote their own version · 40
- openJiuwen-ai/agent-core★ 451same name
- loulanyue/awesome-claude-notes★ 272same name
- Fmarzochi/EGC★ 61same name
- Benkapner/claude-code-basecamp★ 17same name
- komluk/scaffolding★ 15same name
- FaisalAlqarni/sp-ecc★ 9same name
- DetectHensenberg/RAG4JZDQ★ 8same name
- gongyijie85/dsh-ecc★ 8same name
- jdanigo/hydraia★ 8same name
- VoVuongThanhDat/agentflow★ 8same name
30 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects 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-sysSkillconfigure-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 10 projects that use this
loulanyueSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 9 projects that use this
ronmkrSkilldart-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 6 projects that use this
royaluniondesign-sysSkillcontent-hash-cache-pattern
Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.
Also in 14 projects that use this
TironFoxSkillagent-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 5 projects that use this
junimnjwSkillralphinho-rfc-pipeline
RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.
Also in 10 projects that use this
- +1 more from royaluniondesign-sys
In this repository45 other files it gives its agents.
- api-patternsSkill
- app-builderSkill
- templatesSkill
- architectureSkill
- bash-linuxSkill
- behavioral-modesSkill
- brainstormingSkill
- clean-codeSkill
- code-review-checklistSkill
- database-designSkill
- deployment-proceduresSkill
- documentation-templatesSkill
- frontend-designSkill
- 2d-gamesSkill
- 3d-gamesSkill
- game-artSkill
- game-audioSkill
- game-designSkill
- mobile-gamesSkill
- multiplayerSkill
- pc-gamesSkill
- game-developmentSkill
- vr-arSkill
- web-gamesSkill
- geo-fundamentalsSkill
- i18n-localizationSkill
- lint-and-validateSkill
- mcp-builderSkill
- mobile-designSkill
- nextjs-best-practicesSkill
- nodejs-best-practicesSkill
- parallel-agentsSkill
- performance-profilingSkill
- plan-writingSkill
- powershell-windowsSkill
- react-patternsSkill
- red-team-tacticsSkill
- seo-fundamentalsSkill
- server-managementSkill
- systematic-debuggingSkill
- tailwind-patternsSkill
- tdd-workflowSkill
- testing-patternsSkill
- vulnerability-scannerSkill
- webapp-testingSkill
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
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.

