$npx -y skills add omnigentx/jarvis --skill python-patternsPython best practices and patterns. Use when a Dev writes Python code for the Jarvis backend: async/await, typing, pytest, FastAPI patterns.
| 1 | # PYTHON PATTERNS FOR JARVIS |
| 2 | |
| 3 | ## Async / await |
| 4 | ```python |
| 5 | # ✅ Correct: use async for I/O operations |
| 6 | async def fetch_data(url: str) -> dict: |
| 7 | async with httpx.AsyncClient() as client: |
| 8 | response = await client.get(url) |
| 9 | return response.json() |
| 10 | |
| 11 | # ❌ Wrong: blocking I/O inside an async context |
| 12 | def fetch_data(url: str) -> dict: |
| 13 | return requests.get(url).json() # BLOCKS the event loop! |
| 14 | ``` |
| 15 | |
| 16 | ## Type hints |
| 17 | ```python |
| 18 | # ✅ Always use type hints |
| 19 | from typing import Optional |
| 20 | from pydantic import BaseModel |
| 21 | |
| 22 | class AgentConfig(BaseModel): |
| 23 | name: str |
| 24 | instruction: str |
| 25 | skills: list[str] = [] |
| 26 | model: Optional[str] = None |
| 27 | ``` |
| 28 | |
| 29 | ## FastAPI Patterns |
| 30 | ```python |
| 31 | # Router pattern |
| 32 | from fastapi import APIRouter, HTTPException |
| 33 | |
| 34 | router = APIRouter(prefix="/api/v1/agents", tags=["agents"]) |
| 35 | |
| 36 | @router.get("/{agent_id}") |
| 37 | async def get_agent(agent_id: str) -> AgentResponse: |
| 38 | agent = await agent_service.get(agent_id) |
| 39 | if not agent: |
| 40 | raise HTTPException(404, f"Agent {agent_id} not found") |
| 41 | return agent |
| 42 | ``` |
| 43 | |
| 44 | ## Pytest |
| 45 | ```python |
| 46 | # ✅ Fixture-based, descriptive names |
| 47 | import pytest |
| 48 | |
| 49 | @pytest.fixture |
| 50 | def sample_skill(): |
| 51 | return {"name": "test", "description": "Test skill"} |
| 52 | |
| 53 | def test_skill_loads_correct_description(sample_skill): |
| 54 | assert sample_skill["description"] == "Test skill" |
| 55 | |
| 56 | # ✅ Parametrize for multiple cases |
| 57 | @pytest.mark.parametrize("input,expected", [ |
| 58 | ("hello", "HELLO"), |
| 59 | ("", ""), |
| 60 | ]) |
| 61 | def test_uppercase(input, expected): |
| 62 | assert input.upper() == expected |
| 63 | ``` |
| 64 | |
| 65 | ## Error Handling |
| 66 | ```python |
| 67 | # ✅ Specific exceptions, logging |
| 68 | import logging |
| 69 | logger = logging.getLogger(__name__) |
| 70 | |
| 71 | try: |
| 72 | result = await risky_operation() |
| 73 | except SpecificError as e: |
| 74 | logger.error(f"Operation failed: {e}") |
| 75 | raise HTTPException(500, str(e)) |
| 76 | ``` |