python-patterns

A guide to writing maintainable Python, including type hints, asynchronous code for waiting on external work, automated tests, and project organization.

In plain words
What is it for?
Use it when designing Python modules or services, adding types, choosing between synchronous and asynchronous code, structuring dependencies, and testing important behavior.
Why use it?
It helps avoid unclear interfaces, unsuitable use of asynchronous code, hard-to-test business logic, and disorganized Python projects.

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/cosmicstack-labs/mercury-agent-skills/python-patterns
Any agent
npx skills add cosmicstack-labs/mercury-agent-skills --skill python-patterns
Clone the repo
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills

Made for: Claude Code, Codex.

Per session 19 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,955 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.00019 $0.01955
Opus 5 $0.00010 $0.00978
Sonnet 5 $0.00004 $0.00391
Haiku 4.5 $0.00002 $0.00196

Measured 2d ago against content hash 0928e724b152, 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 2d ago.

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.

return await fetch(url)
categories/backend/python-patterns/SKILL.md · 282 lines

How it starts

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

Python Patterns

Write Python that is type-safe, testable, and a joy to maintain.

Core Principles

1. Explicit Over Implicit

Use type hints. Avoid *args and **kwargs when named parameters work. Favor clear interfaces over dynamic flexibility.

2. Composition Over Inheritance

Python's multiple inheritance is powerful but dangerous. Prefer composition and protocols over deep class hierarchies.

3. Async Done Right

Async is a tool for I/O-bound workloads, not a universal default. Use synchronous code for CPU-bound tasks, async for network calls and file I/O.

4. Test-First for Critical Paths

Your business logic should be testable without mocks. Use dependency injection. Keep I/O at the boundaries.


Python Maturity Model

Level Typing Async Testing Structure
1: Script No type hints sync only Manual testing Single file
2: Module Basic types (str, int) Basic asyncio pytest, some coverage Package with __init__.py
3: Package Full type hints with mypy Async with proper patterns pytest + fixtures + mocking src-layout, entry points
4: Service Generics, Protocols, TypedDict Structured concurrency Property-based, integration tests Domain-driven structure
5: Library Precise types, variance annotations Trio / anyio Fuzzing, benchmark tests Public API surface explicit

Target: Level 3+ for production services.


Actionable Guidance

Type Hints

Basic Patterns
from typing import Optional, Union, Sequence, TypeVar, Protocol, Any
from datetime import datetime

# Function signatures
def process_user(
    user_id: int,
    name: str,
    email: Optional[str] = None,
    tags: list[str] | None = None,  # Python 3.10+ union syntax
) -> dict[str, Any]:
    ...

# TypedDict for structured dicts
class UserData(TypedDict, total=False):
    id: int
    name: str
    email: str
    created_at: datetime

# Protocols (structural subtyping)
class Drawable(Protocol):
    def draw(self, context: Any) -> None: ...

def render(item: Drawable) -> None:
    item.draw(...)  # Any object with draw() method works

Read the full file on GitHub · 282 lines

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. 2d ago First seen · 282 lines · 19 tokens per session scan A 0928e724b152

Subscribe to this mod's changes

python-patterns is a skill published in the GitHub repository cosmicstack-labs/mercury-agent-skills (468 stars, last pushed 7d ago), licensed MIT. It adds 19 tokens to every session and 1,955 once invoked, about $0.0001 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.

Related

Other skills, from other repositories

modern-saas-builder

Founder-minded senior product engineer and SaaS architect skill. Use when building, planning, architecting, validating, designing, testing, securing, deploying, or monetizing modern SaaS products, micro-SaaS, web apps, AI agents, Web3/Base applications, agent commerce, or Telegram bots/Mini Apps. Always active when…

lijnati/modern-saas-builder-skills · 98 tokens

claude-md-improver

Audit and improve CLAUDE.md files in repositories. Use when user asks to check, audit, update, improve, or fix CLAUDE.md files. Scans for all CLAUDE.md files, evaluates quality against templates, outputs quality report, then makes targeted updates. Also use when the user mentions "CLAUDE.md maintenance" or "project…

anthropics/claude-plugins-official · 82 tokens

agent-platform-rag-engine-management

Manage and query Agent Platform RAG Engine Corpora and retrieve grounded contexts using the Google GenAI SDK. Use when listing RAG corpora or files, inspecting a corpus, retrieving contexts, or generating content grounded in a RAG corpus. Do not use for standard database queries (use SQL/Spanner skills), Google…

google/skills · 85 tokens

twitter-reader

Read Twitter/X for financial research using opencli (read-only). Use this skill whenever the user wants to read their Twitter feed, search for financial tweets, view bookmarks, look up user profiles, or gather market sentiment from Twitter/X. Triggers include: "check my feed", "search Twitter for", "show my…

himself65/finance-skills · 161 tokens

docx-comment-reply

Reply to comments (批注) in Word .docx/.doc files: extract comment context, draft replies, write threaded replies back, and validate OOXML.

foryourhealth111-pixel/Vibe-Skills · 39 tokens

apple-search-ads

When the user wants to set up, optimize, or scale Apple Search Ads (ASA) campaigns — including keyword bidding, match types, campaign structure, Creative Product Sets, CPP routing, and ROAS optimization. Use when the user mentions "Apple Search Ads", "ASA", "Search Ads", "Search tab ads", "Today tab ads", "CPT"…

Eronred/aso-skills · 127 tokens