Agent skill

Python Anti Patterns

by wshobson in wshobson/agents

A skill your agent uses when reviewing Python code for common anti-patterns to avoid.

MITAuto-check passedDevelopment

Install Python Anti Patterns

skills CLI
$ npx skills add wshobson/agents --skill python-anti-patterns -a claude-code

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

GitHub CLI
$ gh skill install wshobson/agents python-anti-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/wshobson/agents.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/python-development/skills/python-anti-patterns .claude/skills/python-anti-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-anti-patterns
GitHub stars
40k
Token cost
~2k tokens
SKILL.md length
362 words
Files
1
Skills in repo
142
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when reviewing Python code for common anti-patterns to avoid.

  • Reviewing Python code for common anti-patterns to avoid
  • SKILL.md covers When to Use This Skill, Infrastructure Anti-Patterns, Architecture Anti-Patterns and Error Handling Anti-Patterns, plus 5 more sections
  • Needs API_KEY
  • Tasks that involve Error handling

What it does

Python Anti Patterns is an agent skill from wshobson/agents. Use this skill when reviewing Python code for common anti-patterns to avoid. Use as a checklist when reviewing code, before finalizing implementations, or when debugging issues that might stem from known bad practices.

Its SKILL.md is about 2k 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 Error handling and Type safety. It works with Python. The repository describes itself as: Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, Google Antigravity, and Pi. The licence is MIT.

When your agent uses it

  • Reviewing Python code for common anti-patterns to avoid
  • Tasks that involve Error handling
  • Tasks that involve Type safety

Example prompts

  • “/python-anti-patterns”

Requirements

  • Python 3
  • A credential in API_KEY

What it can do on your machine

Read from SKILL.md and the folder at commit 46891e7. 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 these keys or tokens, usually read from environment variables:

    • API_KEY

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

Context cost

Python Anti Patterns loads about 2k tokens when it runs. Until then it costs about 60 tokens; SKILL.md has 362 words of instructions outside code blocks.

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

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 wshobson/agents at commit 46891e7, republished under its MIT licence (© wshobson). 362 words, ~2,041 tokens.

Download SKILL.mdSave it as .claude/skills/python-anti-patterns/SKILL.md (or your agent's skills folder).
name
python-anti-patterns
description
Use this skill when reviewing Python code for common anti-patterns to avoid. Use as a checklist when reviewing code, before finalizing implementations, or when debugging issues that might stem from known bad practices.

Python Anti-Patterns Checklist

A reference checklist of common mistakes and anti-patterns in Python code. Review this before finalizing implementations to catch issues early.

When to Use This Skill

  • Reviewing code before merge
  • Debugging mysterious issues
  • Teaching or learning Python best practices
  • Establishing team coding standards
  • Refactoring legacy code

Note: This skill focuses on what to avoid. For guidance on positive patterns and architecture, see the python-design-patterns skill.

Infrastructure Anti-Patterns

Scattered Timeout/Retry Logic
python
# BAD: Timeout logic duplicated everywhere
def fetch_user(user_id):
    try:
        return requests.get(url, timeout=30)
    except Timeout:
        logger.warning("Timeout fetching user")
        return None

def fetch_orders(user_id):
    try:
        return requests.get(url, timeout=30)
    except Timeout:
        logger.warning("Timeout fetching orders")
        return None

Fix: Centralize in decorators or client wrappers.

python
# GOOD: Centralized retry logic
@retry(stop=stop_after_attempt(3), wait=wait_exponential())
def http_get(url: str) -> Response:
    return requests.get(url, timeout=30)
Double Retry
python
# BAD: Retrying at multiple layers
@retry(max_attempts=3)  # Application retry
def call_service():
    return client.request()  # Client also has retry configured!

Fix: Retry at one layer only. Know your infrastructure's retry behavior.

Hard-Coded Configuration
python
# BAD: Secrets and config in code
DB_HOST = "prod-db.example.com"
API_KEY = "sk-12345"

def connect():
    return psycopg.connect(f"host={DB_HOST}...")

Fix: Use environment variables with typed settings.

python
# GOOD
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    db_host: str = Field(alias="DB_HOST")
    api_key: str = Field(alias="API_KEY")

settings = Settings()

Architecture Anti-Patterns

Exposed Internal Types
python
# BAD: Leaking ORM model to API
@app.get("/users/{id}")
def get_user(id: str) -> UserModel:  # SQLAlchemy model
    return db.query(UserModel).get(id)

Fix: Use DTOs/response models.

python
# GOOD
@app.get("/users/{id}")
def get_user(id: str) -> UserResponse:
    user = db.query(UserModel).get(id)
    return UserResponse.from_orm(user)
Mixed I/O and Business Logic
python
# BAD: SQL embedded in business logic
def calculate_discount(user_id: str) -> float:
    user = db.query("SELECT * FROM users WHERE id = ?", user_id)
    orders = db.query("SELECT * FROM orders WHERE user_id = ?", user_id)
    # Business logic mixed with data access
    if len(orders) > 10:
        return 0.15
    return 0.0

Fix: Repository pattern. Keep business logic pure.

python
# GOOD
def calculate_discount(user: User, orders: list[Order]) -> float:
    # Pure business logic, easily testable
    if len(orders) > 10:
        return 0.15
    return 0.0

Error Handling Anti-Patterns

Bare Exception Handling
python
# BAD: Swallowing all exceptions
try:
    process()
except Exception:
    pass  # Silent failure - bugs hidden forever

Fix: Catch specific exceptions. Log or handle appropriately.

python
# GOOD
try:
    process()
except ConnectionError as e:
    logger.warning("Connection failed, will retry", error=str(e))
    raise
except ValueError as e:
    logger.error("Invalid input", error=str(e))
    raise BadRequestError(str(e))
Ignored Partial Failures
python
# BAD: Stops on first error
def process_batch(items):
    results = []
    for item in items:
        result = process(item)  # Raises on error - batch aborted
        results.append(result)
    return results

Fix: Capture both successes and failures.

python
# GOOD
def process_batch(items) -> BatchResult:
    succeeded = {}
    failed = {}
    for idx, item in enumerate(items):
        try:
            succeeded[idx] = process(item)
        except Exception as e:
            failed[idx] = e
    return BatchResult(succeeded, failed)
Missing Input Validation
python
# BAD: No validation
def create_user(data: dict):
    return User(**data)  # Crashes deep in code on bad input

Fix: Validate early at API boundaries.

python
# GOOD
def create_user(data: dict) -> User:
    validated = CreateUserInput.model_validate(data)
    return User.from_input(validated)

Resource Anti-Patterns

Unclosed Resources
python
# BAD: File never closed
def read_file(path):
    f = open(path)
    return f.read()  # What if this raises?

Fix: Use context managers.

python
# GOOD
def read_file(path):
    with open(path) as f:
        return f.read()
Blocking in Async
python
# BAD: Blocks the entire event loop
async def fetch_data():
    time.sleep(1)  # Blocks everything!
    response = requests.get(url)  # Also blocks!

Fix: Use async-native libraries.

python
# GOOD
async def fetch_data():
    await asyncio.sleep(1)
    async with httpx.AsyncClient() as client:
        response = await client.get(url)

Type Safety Anti-Patterns

Missing Type Hints
python
# BAD: No types
def process(data):
    return data["value"] * 2

Fix: Annotate all public functions.

python
# GOOD
def process(data: dict[str, int]) -> int:
    return data["value"] * 2
Untyped Collections
python
# BAD: Generic list without type parameter
def get_users() -> list:
    ...

Fix: Use type parameters.

python
# GOOD
def get_users() -> list[User]:
    ...

Testing Anti-Patterns

Only Testing Happy Paths
python
# BAD: Only tests success case
def test_create_user():
    user = service.create_user(valid_data)
    assert user.id is not None

Fix: Test error conditions and edge cases.

python
# GOOD
def test_create_user_success():
    user = service.create_user(valid_data)
    assert user.id is not None

def test_create_user_invalid_email():
    with pytest.raises(ValueError, match="Invalid email"):
        service.create_user(invalid_email_data)

def test_create_user_duplicate_email():
    service.create_user(valid_data)
    with pytest.raises(ConflictError):
        service.create_user(valid_data)
Over-Mocking
python
# BAD: Mocking everything
def test_user_service():
    mock_repo = Mock()
    mock_cache = Mock()
    mock_logger = Mock()
    mock_metrics = Mock()
    # Test doesn't verify real behavior

Fix: Use integration tests for critical paths. Mock only external services.

Show full SKILL.md (151 more words)Show less

Quick Review Checklist

Before finalizing code, verify:

  • No scattered timeout/retry logic (centralized)
  • No double retry (app + infrastructure)
  • No hard-coded configuration or secrets
  • No exposed internal types (ORM models, protobufs)
  • No mixed I/O and business logic
  • No bare except Exception: pass
  • No ignored partial failures in batches
  • No missing input validation
  • No unclosed resources (using context managers)
  • No blocking calls in async code
  • All public functions have type hints
  • Collections have type parameters
  • Error paths are tested
  • Edge cases are covered

Common Fixes Summary

Anti-PatternFix
Scattered retry logicCentralized decorators
Hard-coded configEnvironment variables + pydantic-settings
Exposed ORM modelsDTO/response schemas
Mixed I/O + logicRepository pattern
Bare exceptCatch specific exceptions
Batch stops on errorReturn BatchResult with successes/failures
No validationValidate at boundaries with Pydantic
Unclosed resourcesContext managers
Blocking in asyncAsync-native libraries
Missing typesType annotations on all public APIs
Only happy path testsTest errors and edge cases

© wshobson, 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 plugins/python-development/skills/python-anti-patterns of wshobson/agents.

Open the folder on GitHubat commit 46891e7

Compare with similar skills

Python Anti 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 Anti Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Python Anti Patterns this skillwshobson/agents40k—~2kAutomated safety check: PassMIT
Python Patternskurealnum/dotfiles2908 repos~4.1kAutomated safety check: PassNone
Strict Programming Practicescode-yeongyu/oh-my-openagent70k—~9.5kAutomated safety check: PassCustom licence
Python Best PracticesTaoidle/plan-cascade133—~463Automated safety check: PassMIT
Pseudocode To Python CodeArabelaTso/Skills-4-SE253—~2.6kAutomated safety check: PassApache-2.0
Code PatternsAedelon/claude-code-blueprint120—~1.2kAutomated safety check: PassCustom licence

Similar skills

  • Python Patterns

    kurealnum/dotfiles

    Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications.

    290 GitHub starsUsed in 8 repos~4.1k tokens
    DevelopmentAuto-check passed
  • Strict Programming Practices

    code-yeongyu/oh-my-openagent

    Applies strict, type-first coding rules for Python, Rust, TypeScript and Go, loading the matching language reference before the agent writes or edits any code.

    70k GitHub stars~9.5k tokensUpdated today
    DevelopmentAuto-check passed
  • Python Best Practices

    Taoidle/plan-cascade

    Python coding best practices. An agent skill from Taoidle/plan-cascade.

    133 GitHub stars~463 tokensUpdated 6 mo ago
    DevelopmentAuto-check passed
  • Pseudocode To Python Code

    ArabelaTso/Skills-4-SE

    Convert pseudocode, algorithm descriptions, or specifications into complete, executable Python code.

    253 GitHub stars~2.6k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • Code Patterns

    Aedelon/claude-code-blueprint

    Reference patterns for REST APIs, pytest/vitest testing, Docker multi-stage builds, GitHub Actions CI/CD, PostgreSQL, TypeScript generics, Python async, and React Server Components.

    120 GitHub stars~1.2k tokensUpdated 7 mo ago
    DevOps & CloudAuto-check passed
  • Mastra

    majiayu000/claude-skill-registry

    You are an expert in Mastra, the TypeScript framework for building AI agents, RAG pipelines, and workflows.

    666 GitHub starsUsed in 1 repo~1.5k tokens
    AI & LLM EngineeringAuto-check passed

More from wshobson/agents

All 142 skills in this repo
  • Cuts cloud spend across AWS, Azure, GCP and OCI with cost tagging, rightsizing, commitment and spot pricing models, and architecture changes.

    40k GitHub starsUsed in 13 repos~1.7k tokens
    Auto-check passed
  • Billing Automation

    wshobson/agents

    Covers building subscription billing: billing cycles, subscription states, invoice generation, proration, tax handling and dunning for failed payments.

    40k GitHub starsUsed in 12 repos~473 tokens
    Auto-check passed
  • Profiles slow Python code with cProfile and memory profilers, then applies targeted fixes for CPU, memory, I/O and query bottlenecks.

    40k GitHub starsUsed in 12 repos~814 tokens
    Auto-check passed
  • Portfolio Risk Metrics

    wshobson/agents

    Covers portfolio risk measurement with VaR, CVaR, Sharpe, Sortino and drawdown, plus guidance on limits, stress tests and tail risk.

    40k GitHub starsUsed in 12 repos~502 tokens
    Auto-check passed
  • Plans memory headroom, works through out-of-memory failures and watches temperature and power during long ML training jobs on NVIDIA DGX Spark.

    40k GitHub starsUsed in 1 repo~2k tokens
    Auto-check passed
  • Writes unit tests for shell scripts with Bats: error-condition tests, fixtures and mocks, cross-shell checks, parallel runs, helper files and CI integration.

    40k GitHub starsUsed in 11 repos~1.3k tokens
    Auto-check passed

Works with

Categories

Questions about Python Anti Patterns

What does Python Anti Patterns do?

A skill your agent uses when reviewing Python code for common anti-patterns to avoid. Python Anti Patterns is an agent skill from wshobson/agents. Use this skill when reviewing Python code for common anti-patterns to avoid.

When should I use Python Anti Patterns?

Python Anti Patterns fits situations like: reviewing Python code for common anti-patterns to avoid; tasks that involve Error handling; tasks that involve Type safety.

How do I install Python Anti Patterns in Claude Code?

Run `npx skills add wshobson/agents --skill python-anti-patterns -a claude-code`. Or copy the skill folder (plugins/python-development/skills/python-anti-patterns in wshobson/agents) into .claude/skills/python-anti-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Python Anti Patterns in Codex?

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

Can I use Python Anti 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 wshobson/agents --skill python-anti-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-anti-patterns, .gemini/skills/python-anti-patterns, .github/skills/python-anti-patterns and .opencode/skills/python-anti-patterns in your project.

What does Python Anti Patterns need to run?

Going by SKILL.md and its folder, Python Anti Patterns needs credentials named API_KEY. Our summary lists: Python 3; A credential in API_KEY.

Does Python Anti 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 Anti 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 Anti Patterns use?

Python Anti 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 Anti Patterns use?

About 2k tokens (SKILL.md is roughly 8.2k 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 Anti Patterns?

Skills that share tags, products or a category with Python Anti Patterns: Python Patterns (kurealnum/dotfiles, 290 stars), Strict Programming Practices (code-yeongyu/oh-my-openagent, 70k stars), Python Best Practices (Taoidle/plan-cascade, 133 stars) and Pseudocode To Python Code (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 Anti Patterns?

wshobson (a GitHub user) maintains it in wshobson/agents, which has 40,254 GitHub stars. The repository holds 142 skills in this directory. The repository was last updated on October 5, 2026.

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