Agent skill

Python Patterns

by affaan-m in affaan-m/ECC

Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization.

MITAuto-check passedDevelopment

Install Python Patterns

skills CLI
$ npx skills add affaan-m/ECC --skill python-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC python-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.kiro/skills/python-patterns .claude/skills/python-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
python-patterns
GitHub stars
274k
Token cost
~2.3k tokens
SKILL.md length
162 words
Files
1
Skills in repo
657
Repo updated
First seen
Licence
MIT

At a glance

Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization.

  • Working with Python code to apply Pythonic patterns
  • SKILL.md covers Protocol (Duck Typing), Dataclasses as DTOs, Context Managers and Generators, plus 9 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve Type safety

What it does

Python Patterns is an agent skill from affaan-m/ECC. Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Use when working with Python code to apply Pythonic patterns.

Its SKILL.md is about 2.3k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Development, covering Type safety, Design patterns and Async programming. It works with Python. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Working with Python code to apply Pythonic patterns
  • Tasks that involve Type safety
  • Tasks that involve Design patterns

Example prompts

  • “/python-patterns”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Python Patterns loads about 2.3k tokens when it runs. Until then it costs about 61 tokens; SKILL.md has 162 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~61
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 162 words, ~2,333 tokens.

Download SKILL.mdSave it as .claude/skills/python-patterns/SKILL.md (or your agent's skills folder).
name
python-patterns
description
Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Use when working with Python code to apply Pythonic patterns.
metadata.origin
ECC
metadata.globs
**/*.py, **/*.pyi

Python Patterns

This skill provides comprehensive Python patterns extending common design principles with Python-specific idioms.

Protocol (Duck Typing)

Use Protocol for structural subtyping (duck typing with type hints):

python
from typing import Protocol

class Repository(Protocol):
    def find_by_id(self, id: str) -> dict | None: ...
    def save(self, entity: dict) -> dict: ...

# Any class with these methods satisfies the protocol
class UserRepository:
    def find_by_id(self, id: str) -> dict | None:
        # implementation
        pass

    def save(self, entity: dict) -> dict:
        # implementation
        pass

def process_entity(repo: Repository, id: str) -> None:
    entity = repo.find_by_id(id)
    # ... process

Benefits:

  • Type safety without inheritance
  • Flexible, loosely coupled code
  • Easy testing and mocking

Dataclasses as DTOs

Use dataclass for data transfer objects and value objects:

python
from dataclasses import dataclass, field
from typing import Optional

@dataclass
class CreateUserRequest:
    name: str
    email: str
    age: Optional[int] = None
    tags: list[str] = field(default_factory=list)

@dataclass(frozen=True)
class User:
    """Immutable user entity"""
    id: str
    name: str
    email: str

Features:

  • Auto-generated __init__, __repr__, __eq__
  • frozen=True for immutability
  • field() for complex defaults
  • Type hints for validation

Context Managers

Use context managers (with statement) for resource management:

python
from contextlib import contextmanager
from typing import Generator

@contextmanager
def database_transaction(db) -> Generator[None, None, None]:
    """Context manager for database transactions"""
    try:
        yield
        db.commit()
    except Exception:
        db.rollback()
        raise

# Usage
with database_transaction(db):
    db.execute("INSERT INTO users ...")

Class-based context manager:

python
class FileProcessor:
    def __init__(self, filename: str):
        self.filename = filename
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        return False  # Don't suppress exceptions

Generators

Use generators for lazy evaluation and memory-efficient iteration:

python
def read_large_file(filename: str):
    """Generator for reading large files line by line"""
    with open(filename, 'r') as f:
        for line in f:
            yield line.strip()

# Memory-efficient processing
for line in read_large_file('huge.txt'):
    process(line)

Generator expressions:

python
# Instead of list comprehension
squares = (x**2 for x in range(1000000))  # Lazy evaluation

# Pipeline pattern
numbers = (x for x in range(100))
evens = (x for x in numbers if x % 2 == 0)
squares = (x**2 for x in evens)

Decorators

Function Decorators
python
from functools import wraps
import time

def timing(func):
    """Decorator to measure execution time"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f}s")
        return result
    return wrapper

@timing
def slow_function():
    time.sleep(1)
Class Decorators
python
def singleton(cls):
    """Decorator to make a class a singleton"""
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance

@singleton
class Config:
    pass

Async/Await

Async Functions
python
import asyncio
from typing import List

async def fetch_user(user_id: str) -> dict:
    """Async function for I/O-bound operations"""
    await asyncio.sleep(0.1)  # Simulate network call
    return {"id": user_id, "name": "Alice"}

async def fetch_all_users(user_ids: List[str]) -> List[dict]:
    """Concurrent execution with asyncio.gather"""
    tasks = [fetch_user(uid) for uid in user_ids]
    return await asyncio.gather(*tasks)

# Run async code
asyncio.run(fetch_all_users(["1", "2", "3"]))
Async Context Managers
python
class AsyncDatabase:
    async def __aenter__(self):
        await self.connect()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.disconnect()

async with AsyncDatabase() as db:
    await db.query("SELECT * FROM users")

Type Hints

Advanced Type Hints
python
from typing import TypeVar, Generic, Callable, ParamSpec, Concatenate

T = TypeVar('T')
P = ParamSpec('P')

class Repository(Generic[T]):
    """Generic repository pattern"""
    def __init__(self, entity_type: type[T]):
        self.entity_type = entity_type

    def find_by_id(self, id: str) -> T | None:
        # implementation
        pass

# Type-safe decorator
def log_call(func: Callable[P, T]) -> Callable[P, T]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper
Union Types (Python 3.10+)
python
def process(value: str | int | None) -> str:
    match value:
        case str():
            return value.upper()
        case int():
            return str(value)
        case None:
            return "empty"

Dependency Injection

Constructor Injection
python
class UserService:
    def __init__(
        self,
        repository: Repository,
        logger: Logger,
        cache: Cache | None = None
    ):
        self.repository = repository
        self.logger = logger
        self.cache = cache

    def get_user(self, user_id: str) -> User | None:
        if self.cache:
            cached = self.cache.get(user_id)
            if cached:
                return cached

        user = self.repository.find_by_id(user_id)
        if user and self.cache:
            self.cache.set(user_id, user)

        return user

Package Organization

Project Structure
project/
├── src/
│   └── mypackage/
│       ├── __init__.py
│       ├── domain/          # Business logic
│       │   ├── __init__.py
│       │   └── models.py
│       ├── services/        # Application services
│       │   ├── __init__.py
│       │   └── user_service.py
│       └── infrastructure/  # External dependencies
│           ├── __init__.py
│           └── database.py
├── tests/
│   ├── unit/
│   └── integration/
├── pyproject.toml
└── README.md
Module Exports
python
# __init__.py
from .models import User, Product
from .services import UserService

__all__ = ['User', 'Product', 'UserService']

Error Handling

Custom Exceptions
python
class DomainError(Exception):
    """Base exception for domain errors"""
    pass

class UserNotFoundError(DomainError):
    """Raised when user is not found"""
    def __init__(self, user_id: str):
        self.user_id = user_id
        super().__init__(f"User {user_id} not found")

class ValidationError(DomainError):
    """Raised when validation fails"""
    def __init__(self, field: str, message: str):
        self.field = field
        self.message = message
        super().__init__(f"{field}: {message}")
Exception Groups (Python 3.11+)
python
try:
    # Multiple operations
    pass
except* ValueError as eg:
    # Handle all ValueError instances
    for exc in eg.exceptions:
        print(f"ValueError: {exc}")
except* TypeError as eg:
    # Handle all TypeError instances
    for exc in eg.exceptions:
        print(f"TypeError: {exc}")

Property Decorators

python
class User:
    def __init__(self, name: str):
        self._name = name
        self._email = None

    @property
    def name(self) -> str:
        """Read-only property"""
        return self._name

    @property
    def email(self) -> str | None:
        return self._email

    @email.setter
    def email(self, value: str) -> None:
        if '@' not in value:
            raise ValueError("Invalid email")
        self._email = value

Functional Programming

Higher-Order Functions
python
from functools import reduce
from typing import Callable, TypeVar

T = TypeVar('T')
U = TypeVar('U')

def pipe(*functions: Callable) -> Callable:
    """Compose functions left to right"""
    def inner(arg):
        return reduce(lambda x, f: f(x), functions, arg)
    return inner

# Usage
process = pipe(
    str.strip,
    str.lower,
    lambda s: s.replace(' ', '_')
)
result = process("  Hello World  ")  # "hello_world"

When to Use This Skill

  • Designing Python APIs and packages
  • Implementing async/concurrent systems
  • Structuring Python projects
  • Writing Pythonic code
  • Refactoring Python codebases
  • Type-safe Python development

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .kiro/skills/python-patterns of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Compare with similar skills

Python Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Python Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Python Patterns this skillaffaan-m/ECC274k—~2.3kAutomated safety check: PassMIT
Mastering Python SkillSpillwaveSolutions/agent-brain120—~1.4kAutomated safety check: NotesMIT
Python ProJeffallan/claude-skills12k—~1.6kAutomated safety check: PassMIT
Python ExpertRightNow-AI/openfang18k—~765Automated safety check: PassApache-2.0
Module Component GeneratorArabelaTso/Skills-4-SE253—~2.3kAutomated safety check: PassApache-2.0
Python Project SetupFerroxLabs/wayland608—~3.7kAutomated safety check: PassApache-2.0

Similar skills

  • Mastering Python Skill

    SpillwaveSolutions/agent-brain

    Modern Python coaching covering language foundations through advanced production patterns.

    120 GitHub stars~1.4k tokensUpdated 17 days ago
    DevelopmentAuto-check: notes
  • Python Pro

    Jeffallan/claude-skills

    Writes type-annotated Python 3.11+ with async patterns, dataclasses and pytest suites, validated with mypy in strict mode, black and ruff.

    12k GitHub stars~1.6k tokensUpdated 4 days ago
    DevelopmentAuto-check passed
  • Python Expert

    RightNow-AI/openfang

    Python expert for stdlib, packaging, type hints, async/await, and performance optimization

    18k GitHub stars~765 tokensUpdated 3 mo ago
    DevelopmentAuto-check passed
  • Module Component Generator

    ArabelaTso/Skills-4-SE

    Generates complete modules and components from interface contracts and specifications.

    253 GitHub stars~2.3k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • Python Project Setup

    FerroxLabs/wayland

    Guides expert-level Python project initialization with modern tooling: pyproject.toml configuration, uv for dependency management, src layout decisions, mypy strict mode, and ruff for…

    608 GitHub stars~3.7k tokensUpdated yesterday
    DevelopmentAuto-check passed
  • Pydantic AI

    davila7/claude-code-templates

    Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.

    32k GitHub starsUsed in 4 repos~2.9k tokens
    AI & LLM EngineeringAuto-check passed

More from affaan-m/ECC

All 657 skills in this repo
  • Skill Stocktake

    affaan-m/ECC

    Audits your installed Claude skills and commands for quality, with a quick mode for recently changed skills and a full mode that evaluates all of them through subagents.

    274k GitHub starsUsed in 5 repos~1.9k tokens
    Auto-check passed
  • Videodb

    affaan-m/ECC

    Ingest, index, search, edit, and monitor video and audio with the VideoDB Python SDK — upload from files, URLs, or RTSP feeds, build spoken and scene indexes with timestamped search and playable…

    274k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    274k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    274k GitHub stars~2.9k tokensUpdated 2 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    274k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    274k GitHub stars~3.5k tokensUpdated 2 days ago
    Auto-check passed

Works with

Categories

Questions about Python Patterns

What does Python Patterns do?

Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Python Patterns is an agent skill from affaan-m/ECC. Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization.

When should I use Python Patterns?

Python Patterns fits situations like: working with Python code to apply Pythonic patterns; tasks that involve Type safety; tasks that involve Design patterns.

How do I install Python Patterns in Claude Code?

Run `npx skills add affaan-m/ECC --skill python-patterns -a claude-code`. Or copy the skill folder (.kiro/skills/python-patterns in affaan-m/ECC) into .claude/skills/python-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Python Patterns in Codex?

Run `npx skills add affaan-m/ECC --skill python-patterns -a codex`. Or copy the skill folder (.kiro/skills/python-patterns in affaan-m/ECC) into .agents/skills/python-patterns in your project. Codex loads it when a task matches its description.

Can I use Python Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill python-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/python-patterns, .gemini/skills/python-patterns, .github/skills/python-patterns and .opencode/skills/python-patterns in your project.

What does Python Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Python Patterns is instructions for the agent only. Our summary lists: Python 3.

Does Python Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Python Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Python Patterns use?

Python Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Python Patterns use?

About 2.3k tokens (SKILL.md is roughly 9.3k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Python Patterns?

Skills that share tags, products or a category with Python Patterns: Mastering Python Skill (SpillwaveSolutions/agent-brain, 120 stars), Python Pro (Jeffallan/claude-skills, 12k stars), Python Expert (RightNow-AI/openfang, 18k stars) and Module Component Generator (ArabelaTso/Skills-4-SE, 253 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Python Patterns?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 274,360 GitHub stars. The repository holds 657 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.