Python
The Python skill provides expertise in modern Python development including type hints, async patterns, dataclasses, and Pythonic idioms.
When Activated
Section titled “When Activated”- Working with Python files (
.py) - Writing Python scripts or applications
- Using Python frameworks (Django, FastAPI, Flask)
- Data processing and automation
Core Patterns
Section titled “Core Patterns”Type Hints
Section titled “Type Hints”from typing import Optional, List, Dict, Unionfrom collections.abc import Callable
def process_items( items: List[str], callback: Callable[[str], None], config: Optional[Dict[str, Any]] = None) -> List[str]: """Process items with optional callback.""" return [callback(item) for item in items]Async/Await
Section titled “Async/Await”import asynciofrom typing import List
async def fetch_data(url: str) -> dict: async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.json()
async def fetch_all(urls: List[str]) -> List[dict]: return await asyncio.gather(*[fetch_data(url) for url in urls])Context Managers
Section titled “Context Managers”from contextlib import contextmanager
@contextmanagerdef managed_resource(): resource = acquire_resource() try: yield resource finally: release_resource(resource)
# Usagewith managed_resource() as r: r.do_something()Dataclasses
Section titled “Dataclasses”from dataclasses import dataclass, fieldfrom datetime import datetime
@dataclassclass User: id: int email: str name: str created_at: datetime = field(default_factory=datetime.now)
def __post_init__(self): self.email = self.email.lower()Pydantic Models
Section titled “Pydantic Models”from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel): email: EmailStr name: str = Field(min_length=1, max_length=100) password: str = Field(min_length=8)
class Config: str_strip_whitespace = TrueBest Practices
Section titled “Best Practices”- Use type hints for all public functions
- Use dataclasses or Pydantic for data models
- Prefer context managers for resource management
- Use async for I/O-bound operations
- Follow PEP 8 style guidelines
Common Pitfalls
Section titled “Common Pitfalls”Mutable Default Arguments
Section titled “Mutable Default Arguments”# ❌ BAD: Mutable defaultdef add_item(item, items=[]): items.append(item) return items
# ✅ GOOD: Use None and initializedef add_item(item, items=None): if items is None: items = [] items.append(item) return itemsNot Closing Resources
Section titled “Not Closing Resources”# ❌ BAD: Manual resource managementfile = open('data.txt')data = file.read()file.close()
# ✅ GOOD: Use with statementwith open('data.txt') as file: data = file.read()Blocking in Async
Section titled “Blocking in Async”# ❌ BAD: Blocking call in async functionasync def process(): result = expensive_cpu_work() # Blocks event loop return result
# ✅ GOOD: Run in thread poolasync def process(): loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, expensive_cpu_work) return resultCatching Bare Exceptions
Section titled “Catching Bare Exceptions”# ❌ BAD: Catching everythingtry: risky_operation()except: handle_error()
# ✅ GOOD: Specific exceptionstry: risky_operation()except (ValueError, TypeError) as e: handle_error(e)Integration with Frameworks
Section titled “Integration with Frameworks”With FastAPI
Section titled “With FastAPI”See FastAPI skill for API development patterns.
With Django
Section titled “With Django”See Django skill for web application patterns.
With pytest
Section titled “With pytest”See pytest skill for testing patterns.
Related Skills
Section titled “Related Skills”- FastAPI - REST API development
- Django - Web applications
- pytest - Testing framework
- PostgreSQL - Database integration