python-patterns

A guide to current Python coding practices, including type hints, asynchronous code, data classes, error handling, and performance.

In plain words
What is it for?
Use it when building Python modules or services, checking public functions, handling input and errors, or deciding when asynchronous code is appropriate.
Why use it?
It helps developers write new Python code, review existing code, or update older code with clearer and more maintainable patterns.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/chandrudp29/skillhub/python-patterns
Any agent
npx skills add chandrudp29/skillhub --skill python-patterns
Clone the repo
git clone --depth 1 https://github.com/chandrudp29/skillhub

Made for: Claude Code, Codex.

Per session 41 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,531 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00041 $0.01531
Opus 5 $0.00020 $0.00766
Sonnet 5 $0.00008 $0.00306
Haiku 4.5 $0.00004 $0.00153

Measured yesterday against content hash 8df2c537650e, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

python-patterns scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

result = requests.get(url) # blocks the event loop for everyone
skills/python-patterns/SKILL.md · 209 lines

How it starts

The opening of the file, as written. The whole thing — 209 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python Patterns

Modern Python (3.10+) patterns for production code. Specific, opinionated, actionable.

When to Use

  • Writing new Python modules or services
  • Reviewing Python code for quality
  • Modernizing Python 2-era or early Python 3 code
  • Debugging subtle Python behavior

Type Hints

Always type hint public functions. It's documentation that tools can check.

# Good — clear what goes in and what comes out
def chunk_text(text: str, max_tokens: int = 512) -> list[str]:
    ...

# Good — complex types use type aliases
from typing import TypeAlias
JsonDict: TypeAlias = dict[str, "JsonValue"]
JsonValue: TypeAlias = str | int | float | bool | None | list["JsonValue"] | JsonDict

# Good — use | for unions (Python 3.10+), not Optional
def find_user(user_id: int) -> User | None:
    ...

# Good — use dataclass for structured data, not plain dicts
from dataclasses import dataclass, field

@dataclass
class EmbeddingResult:
    text: str
    vector: list[float]
    model: str
    token_count: int
    metadata: dict[str, str] = field(default_factory=dict)

Async Patterns

Use async for I/O-bound work. Don't use it for CPU-bound work.

import asyncio
import httpx

# Good — concurrent I/O with asyncio.gather
async def fetch_all(urls: list[str]) -> list[dict]:
    async with httpx.AsyncClient() as client:
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks, return_exceptions=True)
    return [r.json() for r in responses if not isinstance(r, Exception)]

# Good — async context manager for resource cleanup
class DatabasePool:
    async def __aenter__(self):
        self._conn = await connect()
        return self._conn

    async def __aexit__(self, *args):
        await self._conn.close()

# Good — async generator for streaming
async def stream_llm_response(prompt: str):
    async with client.stream("POST", "/completions", json={"prompt": prompt}) as r:
        async for chunk in r.aiter_lines():
            if chunk:
                yield chunk

# BAD — blocking I/O in async code
async def bad_example():
    import requests
    result = requests.get(url)  # blocks the event loop for everyone

Read the full file on GitHub · 209 lines

Files

What ships with it

1 file beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 209 lines · 41 tokens per session scan A 8df2c537650e

Subscribe to this mod's changes

python-patterns is a skill published in the GitHub repository chandrudp29/skillhub (13 stars, last pushed 2mo ago), licensed MIT. It adds 41 tokens to every session and 1,531 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.