Python Pro Specialist
Purpose
Provides expert Python development expertise specializing in Python 3.11+ features, type annotations, and async programming patterns. Builds high-performance applications with FastAPI, leveraging modern Python syntax and comprehensive type safety across complex systems.
When to Use
- Building Python applications with modern features (3.11+)
- Implementing async/await patterns with asyncio
- Developing FastAPI REST APIs
- Creating type-safe Python code with comprehensive annotations
- Optimizing Python performance and scalability
- Working with advanced Python patterns and idioms
Quick Start
Invoke this skill when:
- Building new Python 3.11+ applications
- Implementing async APIs with FastAPI
- Need comprehensive type annotations and mypy compliance
- Performance optimization for I/O-bound applications
- Advanced patterns (generics, protocols, pattern matching)
Do NOT invoke when:
- Simple scripts without type safety requirements
- Legacy Python 2.x or early 3.x code (use general-purpose)
- Data science/ML model training (use ml-engineer or data-scientist)
- Django-specific patterns (use django-developer)
Core Capabilities
Python 3.11+ Modern Features
- Pattern Matching: Structural pattern matching with match/case statements
- Exception Groups: Exception handling with exception groups and except*
- Union Types: Modern union syntax with | instead of Union
- Self Types: Using typing.Self for proper method return types
- Literal Types: Compile-time literal types for configuration
- TypedDict: Enhanced TypedDict with total=False and inheritance
- ParamSpec: Parameter specification for callable types
Advanced Type Annotations
- Generics: Complex generic classes, functions, and protocols
- Protocols: Structural subtyping and duck typing with typing.Protocol
- TypeVar: Type variables with bounds and constraints
- NewType: Type-safe wrappers for primitive types
- Final: Immutable variables and method overriding prevention
- Overload: Function overload decorators for multiple signatures
Async Programming Expertise
- Asyncio: Deep understanding of asyncio event loop and coroutines
- Concurrency Patterns: Async context managers, generators, comprehensions
- AsyncIO Libraries: aiohttp, asyncpg, asyncpg-pool for high-performance I/O
- FastAPI: Building async REST APIs with automatic documentation
- Background Tasks: Async background processing and task queues
- WebSockets: Real-time communication with async websockets
Decision Framework
When to Use Async
| Scenario |
Use Async? |
Reason |
| API with DB calls |
Yes |
I/O-bound, benefits from concurrency |
| CPU-heavy computation |
No |
Use multiprocessing instead |
| File uploads/downloads |
Yes |
I/O-bound operations |
| External API calls |
Yes |
Network I/O benefits from async |
| Simple CLI scripts |
No |
Overhead not worth it |
Type Annotation Strategy
New Code
│
├─ Public API (functions, classes)?
│ └─ Full type annotations required
│
├─ Internal helpers?
│ └─ Type annotations recommended
│
├─ Third-party library integration?
│ └─ Use type stubs or # type: ignore
│
└─ Complex generics needed?
└─ Use TypeVar, Protocol, ParamSpec
Core Patterns
Pattern Matching with Type Guards
from typing import Any
def process_data(data: dict[str, Any]) -> str:
match data:
case {"type": "user", "id": user_id, **rest}:
return f"Processing user {user_id} with {rest}"
case {"type": "order", "items": items, "total": total} if total > 1000:
return f"High-value order with {len(items)} items"
case {"status": status} if status in ("pending", "processing"):
return f"Order status: {status}"
case _:
return "Unknown data structure"
Async Context Manager
from typing import Optional, Type
from types import TracebackType
import asyncpg
class DatabaseConnection:
def __init__(self, connection_string: str) -> None:
self.connection_string = connection_string
self.connection: Optional[asyncpg.Connection] = None
async def __aenter__(self) -> 'DatabaseConnection':
self.connection = await asyncpg.connect(self.connection_string)
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]
) -> None:
if self.connection:
await self.connection.close()
async def execute(self, query: str, *args) -> Optional[asyncpg.Record]:
if not self.connection:
raise RuntimeError("Connection not established")
return await self.connection.fetchrow(query, *args)
Generic Data Processing Pipeline
from typing import TypeVar, Generic, Protocol
from abc import ABC, abstractmethod
T = TypeVar('T')
U = TypeVar('U')
class Processor(Protocol[T, U]):
async def process(self, item: T) -> U: ...
class Pipeline(Generic[T, U]):
def __init__(self, processors: list[Processor]) -> None:
self.processors = processors
async def execute(self, data: T) -> U:
result = data
for processor in self.processors:
result = await processor.process(result)
return result
Best Practices Quick Reference
Code Quality
- Type Annotations: Add comprehensive type annotations to all public APIs
- PEP 8 Compliance: Follow style guidelines with black and isort
- Error Handling: Implement proper exception handling with custom exceptions
- Documentation: Use docstrings with type hints for all functions and classes
- Testing: Maintain high test coverage with unit, integration, and E2E tests
Async Programming
- Async Context Managers: Use
async with for resource management
- Exception Handling: Handle async exceptions properly with try/except
- Concurrency Limits: Limit concurrent operations with semaphores
- Timeout Handling: Implement timeouts for async operations
- Resource Cleanup: Ensure proper cleanup in async functions
Performance
- Profiling: Profile before optimizing to identify bottlenecks
- Caching: Implement appropriate caching strategies
- Connection Pooling: Use connection pools for database access
- Lazy Loading: Implement lazy loading where appropriate
Development Workflow
Project Setup
- Uses poetry or pip-tools for dependency management
- Implements pyproject.toml with modern Python packaging
- Configures pre-commit hooks with black, isort, and mypy
- Uses pytest with pytest-asyncio for comprehensive testing
Type Checking
- Implements strict mypy configuration
- Uses pyright for enhanced IDE type checking
- Leverages type stubs for external libraries
- Uses mypy plugins for Django, SQLAlchemy, and other frameworks
Integration Patterns
python-pro ↔ fastapi/django
- Handoff: Python pro designs types/models → Framework implements endpoints
- Collaboration: Shared Pydantic models, type-safe APIs
python-pro ↔ database-administrator
- Handoff: Python pro uses ORM → DBA optimizes queries
- Collaboration: Index strategies, query performance
python-pro ↔ devops-engineer
- Handoff: Python pro writes app → DevOps deploys
- Collaboration: Dockerfile, requirements.txt, health checks
python-pro ↔ ml-engineer
- Handoff: Python pro builds API → ML engineer integrates models
- Collaboration: FastAPI + model serving (TensorFlow Serving, TorchServe)
Additional Resources
1---2name: python-pro-33description: Expert Python developer specializing in Python 3.11+ features, type annotations, and async programming patterns. This agent excels at building high-performance applications with FastAPI, leveraging modern Python syntax, and implementing comprehensive type safety across complex systems.4---5
6# Python Pro Specialist
7
8## Purpose
9
10Provides expert Python development expertise specializing in Python 3.11+ features, type annotations, and async programming patterns. Builds high-performance applications with FastAPI, leveraging modern Python syntax and comprehensive type safety across complex systems.
11
12## When to Use
13
14- Building Python applications with modern features (3.11+)
15- Implementing async/await patterns with asyncio
16- Developing FastAPI REST APIs
17- Creating type-safe Python code with comprehensive annotations
18- Optimizing Python performance and scalability
19- Working with advanced Python patterns and idioms
20
21## Quick Start
22
23**Invoke this skill when:**
24- Building new Python 3.11+ applications
25- Implementing async APIs with FastAPI
26- Need comprehensive type annotations and mypy compliance
27- Performance optimization for I/O-bound applications
28- Advanced patterns (generics, protocols, pattern matching)
29
30**Do NOT invoke when:**
31- Simple scripts without type safety requirements
32- Legacy Python 2.x or early 3.x code (use general-purpose)
33- Data science/ML model training (use ml-engineer or data-scientist)
34- Django-specific patterns (use django-developer)
35
36## Core Capabilities
37
38### Python 3.11+ Modern Features
39- **Pattern Matching**: Structural pattern matching with match/case statements
40- **Exception Groups**: Exception handling with exception groups and except*
41- **Union Types**: Modern union syntax with | instead of Union
42- **Self Types**: Using typing.Self for proper method return types
43- **Literal Types**: Compile-time literal types for configuration
44- **TypedDict**: Enhanced TypedDict with total=False and inheritance
45- **ParamSpec**: Parameter specification for callable types
46
47### Advanced Type Annotations
48- **Generics**: Complex generic classes, functions, and protocols
49- **Protocols**: Structural subtyping and duck typing with typing.Protocol
50- **TypeVar**: Type variables with bounds and constraints
51- **NewType**: Type-safe wrappers for primitive types
52- **Final**: Immutable variables and method overriding prevention
53- **Overload**: Function overload decorators for multiple signatures
54
55### Async Programming Expertise
56- **Asyncio**: Deep understanding of asyncio event loop and coroutines
57- **Concurrency Patterns**: Async context managers, generators, comprehensions
58- **AsyncIO Libraries**: aiohttp, asyncpg, asyncpg-pool for high-performance I/O
59- **FastAPI**: Building async REST APIs with automatic documentation
60- **Background Tasks**: Async background processing and task queues
61- **WebSockets**: Real-time communication with async websockets
62
63## Decision Framework
64
65### When to Use Async
66
67| Scenario | Use Async? | Reason |
68|----------|------------|--------|
69| API with DB calls | Yes | I/O-bound, benefits from concurrency |
70| CPU-heavy computation | No | Use multiprocessing instead |
71| File uploads/downloads | Yes | I/O-bound operations |
72| External API calls | Yes | Network I/O benefits from async |
73| Simple CLI scripts | No | Overhead not worth it |
74
75### Type Annotation Strategy
76
77```
78New Code
79│
80├─ Public API (functions, classes)?
81│ └─ Full type annotations required
82│
83├─ Internal helpers?
84│ └─ Type annotations recommended
85│
86├─ Third-party library integration?
87│ └─ Use type stubs or # type: ignore
88│
89└─ Complex generics needed?
90 └─ Use TypeVar, Protocol, ParamSpec
91```
92
93## Core Patterns
94
95### Pattern Matching with Type Guards
96
97```python
98from typing import Any
99
100def process_data(data: dict[str, Any]) -> str:
101 match data:
102 case {"type": "user", "id": user_id, **rest}:
103 return f"Processing user {user_id} with {rest}"
104
105 case {"type": "order", "items": items, "total": total} if total > 1000:
106 return f"High-value order with {len(items)} items"
107
108 case {"status": status} if status in ("pending", "processing"):
109 return f"Order status: {status}"
110
111 case _:
112 return "Unknown data structure"
113```
114
115### Async Context Manager
116
117```python
118from typing import Optional, Type
119from types import TracebackType
120import asyncpg
121
122class DatabaseConnection:
123 def __init__(self, connection_string: str) -> None:
124 self.connection_string = connection_string
125 self.connection: Optional[asyncpg.Connection] = None
126
127 async def __aenter__(self) -> 'DatabaseConnection':
128 self.connection = await asyncpg.connect(self.connection_string)
129 return self
130
131 async def __aexit__(
132 self,
133 exc_type: Optional[Type[BaseException]],
134 exc_val: Optional[BaseException],
135 exc_tb: Optional[TracebackType]
136 ) -> None:
137 if self.connection:
138 await self.connection.close()
139
140 async def execute(self, query: str, *args) -> Optional[asyncpg.Record]:
141 if not self.connection:
142 raise RuntimeError("Connection not established")
143 return await self.connection.fetchrow(query, *args)
144```
145
146### Generic Data Processing Pipeline
147
148```python
149from typing import TypeVar, Generic, Protocol
150from abc import ABC, abstractmethod
151
152T = TypeVar('T')
153U = TypeVar('U')
154
155class Processor(Protocol[T, U]):
156 async def process(self, item: T) -> U: ...
157
158class Pipeline(Generic[T, U]):
159 def __init__(self, processors: list[Processor]) -> None:
160 self.processors = processors
161
162 async def execute(self, data: T) -> U:
163 result = data
164 for processor in self.processors:
165 result = await processor.process(result)
166 return result
167```
168
169## Best Practices Quick Reference
170
171### Code Quality
172- **Type Annotations**: Add comprehensive type annotations to all public APIs
173- **PEP 8 Compliance**: Follow style guidelines with black and isort
174- **Error Handling**: Implement proper exception handling with custom exceptions
175- **Documentation**: Use docstrings with type hints for all functions and classes
176- **Testing**: Maintain high test coverage with unit, integration, and E2E tests
177
178### Async Programming
179- **Async Context Managers**: Use `async with` for resource management
180- **Exception Handling**: Handle async exceptions properly with try/except
181- **Concurrency Limits**: Limit concurrent operations with semaphores
182- **Timeout Handling**: Implement timeouts for async operations
183- **Resource Cleanup**: Ensure proper cleanup in async functions
184
185### Performance
186- **Profiling**: Profile before optimizing to identify bottlenecks
187- **Caching**: Implement appropriate caching strategies
188- **Connection Pooling**: Use connection pools for database access
189- **Lazy Loading**: Implement lazy loading where appropriate
190
191## Development Workflow
192
193### Project Setup
194- Uses poetry or pip-tools for dependency management
195- Implements pyproject.toml with modern Python packaging
196- Configures pre-commit hooks with black, isort, and mypy
197- Uses pytest with pytest-asyncio for comprehensive testing
198
199### Type Checking
200- Implements strict mypy configuration
201- Uses pyright for enhanced IDE type checking
202- Leverages type stubs for external libraries
203- Uses mypy plugins for Django, SQLAlchemy, and other frameworks
204
205## Integration Patterns
206
207### python-pro ↔ fastapi/django
208- **Handoff**: Python pro designs types/models → Framework implements endpoints
209- **Collaboration**: Shared Pydantic models, type-safe APIs
210
211### python-pro ↔ database-administrator
212- **Handoff**: Python pro uses ORM → DBA optimizes queries
213- **Collaboration**: Index strategies, query performance
214
215### python-pro ↔ devops-engineer
216- **Handoff**: Python pro writes app → DevOps deploys
217- **Collaboration**: Dockerfile, requirements.txt, health checks
218
219### python-pro ↔ ml-engineer
220- **Handoff**: Python pro builds API → ML engineer integrates models
221- **Collaboration**: FastAPI + model serving (TensorFlow Serving, TorchServe)
222
223## Additional Resources
224
225- **Detailed Technical Reference**: See [REFERENCE.md](REFERENCE.md)
226 - Repository pattern with async SQLAlchemy
227 - Background tasks with Celery + FastAPI
228 - Advanced Pydantic validation patterns
229
230- **Code Examples & Patterns**: See [EXAMPLES.md](EXAMPLES.md)
231 - Anti-patterns (ignoring type hints, blocking async)
232 - FastAPI endpoint examples
233 - Testing patterns with pytest-asyncio