agentleFS
peopleforresterpeopleforrester/claude-dotfiles/skills/patterns/python-patterns/SKILL.md

python-patterns

Skill3 starsChanged 8 months agoMITView on GitHub

Python 3.10+ best practices, patterns, and idioms. Covers type hints, async, dataclasses, protocols, and modern Python tooling. Use when writing Python code, reviewing Python patterns, or learning idiomatic Python.

38 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use kotlin-testing, nuxt4-patterns and 8 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • tpavanipradeepSkill

    kotlin-testing

    Kotlin testing patterns with Kotest, MockK, coroutine testing, property-based testing, and Kover coverage. Follows TDD methodology with idiomatic Kotlin practices.

    Also in 6 projects that use this

  • mryeastcodeSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 5 projects that use this

  • InfopibeSkill

    ralphinho-rfc-pipeline

    RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.

    Also in 9 projects that use this

  • saxon-ySkill

    configure-ecc

    Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.

    Also in 11 projects that use this

  • InfopibeSkill

    swift-protocol-di-testing

    Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.

    Also in 9 projects that use this

  • mryeastcodeSkill

    pytorch-patterns

    PyTorch deep learning patterns and best practices for building robust, efficient, and reproducible training pipelines, model architectures, and data loading.

    Also in 8 projects that use this

  • +1 more from Infopibe
  • +1 more from mryeastcode

The file

Files
SKILL.md

Python Patterns

Modern Python 3.10+ patterns and best practices.

Type Hints

Strict Typing

from typing import TypeVar, Protocol, Optional
from collections.abc import Sequence

T = TypeVar('T')

def first_or_none(items: Sequence[T]) -> Optional[T]:
    return items[0] if items else None

Protocols (Structural Typing)

from typing import Protocol, runtime_checkable

@runtime_checkable
class Renderable(Protocol):
    def render(self) -> str: ...

class HtmlWidget:
    def render(self) -> str:
        return "<div>widget</div>"

def display(item: Renderable) -> None:
    print(item.render())

display(HtmlWidget())  # Works - structural match

TypedDict for Structured Data

from typing import TypedDict, NotRequired

class UserConfig(TypedDict):
    name: str
    email: str
    theme: NotRequired[str]  # Optional key

Dataclasses and Immutability

Frozen Dataclasses

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

Pydantic for Validation

from pydantic import BaseModel, Field, field_validator

class CreateUser(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    email: str
    age: int = Field(ge=0, le=150)

    @field_validator('email')
    @classmethod
    def validate_email(cls, v: str) -> str:
        if '@' not in v:
            raise ValueError('Invalid email')
        return v.lower()

Async Patterns

Structured Concurrency

import asyncio

async def fetch_all(urls: list[str]) -> list[str]:
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(url)) for url in urls]
    return [t.result() for t in tasks]

Async Context Managers

from contextlib import asynccontextmanager
from typing import AsyncIterator

@asynccontextmanager
async def db_transaction() -> AsyncIterator[Connection]:
    conn = await get_connection()
    try:
        yield conn
        await conn.commit()
    except Exception:
        await conn.rollback()
        raise
    finally:
        await conn.close()

Error Handling

Result Pattern

from dataclasses import dataclass
from typing import Generic, TypeVar, Union

T = TypeVar('T')
E = TypeVar('E', bound=Exception)

@dataclass(frozen=True)
class Ok(Generic[T]):
    value: T

@dataclass(frozen=True)
class Err(Generic[E]):
    error: E

Result = Union[Ok[T], Err[E]]

def divide(a: float, b: float) -> Result[float, ValueError]:
    if b == 0:
        return Err(ValueError("Division by zero"))
    return Ok(a / b)

Match Statements (3.10+)

match command.split():
    case ["quit"]:
        sys.exit(0)
    case ["go", direction]:
        move(direction)
    case ["get", item] if item in inventory:
        pick_up(item)
    case _:
        print(f"Unknown command: {command}")

Tooling

ToolPurposeCommand
uvPackage managementuv add package
ruffLinting + formattingruff check . && ruff format .
mypyType checkingmypy src/ --strict
pytestTestingpytest -xvs
pyrightType checking (fast)pyright src/

Checklist

  • Type hints on all public functions
  • Dataclasses for data containers (not plain dicts)
  • Async for I/O-bound operations
  • Match statements for complex branching (3.10+)
  • Protocols for duck typing
  • Pydantic for input validation
  • uv for package management
  • ruff for linting and formatting

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.