Loading...
Loading...
Python patterns for CLI tools, async concurrency, and backend services. Use when working with Python code, building CLI apps, FastAPI services, async with asyncio, background jobs, or configuring uv, ruff, ty, pytest, or pyproject.toml.
npx skill4agent add iliaal/ai-skills python-services| Tool | Replaces | Purpose |
|---|---|---|
| uv | pip, virtualenv, pyenv, pipx | Package/dependency management |
| ruff | flake8, black, isort | Linting + formatting |
| ty | mypy, pyright | Type checking (Astral, faster) |
uv init --package myprojectuv inituv add <pkg>uv add --group dev <pkg>uv run <cmd>uv add --upgrade <pkg>uv tree --outdateduv.lock[dependency-groups][project.optional-dependencies]ruff check --fix . && ruff format .src/mypackage/
__init__.py
main.py
services/
models/
tests/
conftest.py
test_main.py
pyproject.toml| Workload | Approach |
|---|---|
| Many concurrent I/O calls | |
| CPU-bound computation | |
| Mixed I/O + CPU | |
| Simple scripts, few connections | Stay synchronous |
asyncio.gather(*tasks)return_exceptions=Trueasyncio.TaskGroupgatherasyncio.Semaphore(n)asyncio.wait_for(coro, timeout=N)asyncio.Queueasyncio.Lockasyncio.to_thread(sync_fn)aiohttphttpx.AsyncClientCancelledErrorasync forfrom concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=4) as pool:
results = list(pool.map(cpu_task, items))/jobs/{id}@app.task(bind=True, max_retries=3, autoretry_for=(ConnectionError,))raise self.retry(countdown=2**self.request.retries * 60)chain(a.s(), b.s())group(...)chord(group, callback)from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type
@retry(
retry=retry_if_exception_type((ConnectionError, TimeoutError)),
stop=stop_after_attempt(5) | stop_after_delay(60),
wait=wait_exponential_jitter(initial=1, max=30),
before_sleep=log_retry_attempt,
)
def call_api(url: str) -> dict: ...@fail_safe(default=[])functools.lru_cache(maxsize=N)functools.cache@traced @with_timeout(30) @retry(...)httpx.AsyncClient()pool_sizemax_overflowaiohttp.TCPConnector(limit=N)BaseSettingsmodel_validator/health/ready/ready/healthJSONRendererTimeStampermerge_contextvarsX-Correlation-IDcontextvarsLogRecordFormatterlogging.Formatter.format()record.namecaplogLogger.callHandlersLogRecordif r.name == "src.services.foo"LOGGER_TO_MODEL.get(record.name)logging.Filterrecord.short_name%(short_name)sformatMessageformattryfinallyuv run pytest --cov --cov-report=html--lf-x-k "pattern"--pdbconftest.py@pytest.fixture(scope="session")scope="function"tmp_path@pytest.mark.parametrize("input,expected", [...], ids=["empty", "single", "overflow"])autospec=Trueassert_awaited_once()pyproject.toml[tool.pytest.ini_options]markers = ["slow", "integration"]-m "not slow"class Renderable(Protocol)@contextmanager__exit__ValueErrorTypeErrorKeyErrorExceptionraise ServiceError("upload failed") from eBatchResult(succeeded={}, failed={})BaseModelfield_validatoria-postgresql--autogenerateBaseModelresponse_modelresponse_modelmodel_config = ConfigDict(extra="forbid")field: str | None = NoneField(deprecated=True){"error": {"code": "...", "message": "...", "details": ...}}@app.exception_handlerRequestValidationErrorHTTPExceptionuv run pytestuv run ruff check .uv run ty check .uv run pytest --cov