python-expert
Use for Python development requiring async programming, type system expertise, testing patterns, or performance optimization.
When & Why to Use This Skill
The Python Expert skill provides elite-level guidance for modern Python 3.13+ development, specializing in high-performance backend architecture, complex asynchronous programming, and robust type safety. It empowers developers to build scalable APIs using frameworks like FastAPI and Django, implement rigorous testing patterns with pytest, and optimize code for both security and execution speed while adhering to SOLID principles and PEP 8 standards.
Use Cases
- Developing high-concurrency backend services using asyncio, TaskGroups, and structured concurrency patterns.
- Refactoring legacy Python codebases to implement modern type hints (3.10+), structural typing with Protocols, and advanced variance.
- Designing comprehensive testing suites using pytest, including complex async mocking, integration tests, and automated cleanup.
- Optimizing application performance through cProfile analysis, memory-efficient data structures like __slots__, and effective caching strategies.
- Conducting security-focused code reviews to implement AES-256-GCM encryption, Argon2 password hashing, and protection against SQL injection or CSRF.
| name | python-expert |
|---|---|
| description | Use for Python development requiring async programming, type system expertise, testing patterns, or performance optimization. |
Python Expert
Elite Python 3.13+ expertise for backend development, testing, async programming, and type systems.
When to Use
- Async/await, asyncio, concurrency patterns
- Type errors or complex annotations
- Writing/debugging tests (pytest, async, mocking)
- Performance optimization
- Security review
- Backend architecture (FastAPI, Django, SQLAlchemy)
Core Expertise
Python Mastery: Decorators, context managers, metaclasses, descriptors, generators, coroutines, data model, GIL internals
Backend: FastAPI/Django/Flask, PostgreSQL/Redis/MongoDB, SQLAlchemy/Django ORM, REST/GraphQL/WebSockets/gRPC, OAuth2/JWT, microservices
Code Standards
- Full type hints, Google/NumPy docstrings, 88-char lines
- PEP 8 naming, SOLID principles, secure by default
- Use f-strings for formatting, focused small functions
Testing
pytest: Use setup_method, pytest.raises, @patch for mocking
Async: Use anyio for test fixtures, AsyncMock for mocking async functions
Integration: In-memory SQLite fixtures with proper cleanup
All network calls must be mocked
Async/Await
asyncio.run()for entry,TaskGroupfor structured concurrency (preferred overgather())asyncio.timeout()for timeouts,Semaphorefor rate limiting- Handle cancellation with try/finally, use
ExceptionGroupfor multiple errors - Type:
async def foo() -> TorAwaitable[T]
Type System
Modern syntax (Python 3.10+): list[str], dict[str, int], str | None
Variance: dict invariant, Mapping covariant—use Mapping[K, V] when needed
Advanced: Self for fluent methods, ParamSpec for decorator typing, TypedDict
Minimize Any:
- Use
Protocolfor structural typing instead ofAny - Use
TypedDictfor dicts with known structure instead ofdict[str, Any] - Document why
Anyis necessary when it must be used
Common fixes: Mixed type ops, SQLAlchemy column assignments, API response access Atomic processing: Fix ALL type errors in file with single edit
Patterns
# Dataclass with slots (memory efficient)
@dataclass(slots=True)
class User:
name: str
email: str
tags: list[str] = field(default_factory=list)
def __post_init__(self):
if not self.name: raise ValueError("Name required")
# Pattern matching (3.10+)
match response.status:
case 200: return response.json()
case 404: raise NotFoundError()
case _: raise APIError(response.status)
Prefer: Dependency injection over singletons, @cache for memoized instances
Security
- Validate/sanitize all inputs, parameterized SQL queries only
- Rate limiting, CORS/CSRF protection, secure sessions
- Avoid dynamic code evaluation and unsafe serialization with untrusted data
Cryptography:
- Forbidden: MD5, SHA-1, DES/3DES, RC4, custom crypto
- Required: SHA-256+ for hashing, AES-256-GCM for encryption, Argon2/scrypt for passwords
- Use
secretsmodule for tokens,cryptographypackage for crypto operations
Performance
- Profile first (cProfile, timeit), optimize real bottlenecks
- Sets for O(1) lookup, deque for queues, Counter for counting
- Generators for large data,
__slots__for memory @cache(unbounded) or@lru_cache(bounded) for memoization- Eager loading (N+1), connection pooling, async I/O
Pitfalls
# Mutable defaults: use None, then check identity
def f(items=None):
if items is None:
items = [] # Don't use `or []` - empty list is falsy!
return items
# Late binding: capture with default arg
funcs = [lambda x=i: x for i in range(3)]
Avoid: God classes, spaghetti code, magic numbers, copy-paste, bare except:
Error Handling
Custom exception hierarchies, structured JSON logging, circuit breakers, retry with backoff, graceful degradation
Tooling
ruff check . # lint
ruff format . # format
pyright . # typecheck
Stack: uv, httpx/aiohttp/anyio, pydantic
Cleanup
Remove before completion: debug-*.py, test-*.py, __pycache__/, *.pyc, *_REPORT.md