Skip to main content
skill CX Codex

python-anti-patterns — Claude skill: a Python anti-pattern checklist

A checklist skill for common Python mistakes. The agent runs it over your code before merge or while debugging.

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add wshobson/agents
/plugin install python-development@claude-code-workflows
Open on GitHub

What python-anti-patterns does

The skill hands the agent a reference list of Python anti-patterns and tells it to review against that list before finalizing an implementation. Each entry shows bad and good code side by side: scattered timeout and retry logic, double retries across layers, hard-coded secrets and config, ORM models leaking into API responses, SQL buried in business logic, bare except Exception, batch jobs that abort on the first failure, unclosed files, blocking calls inside async code, missing type hints, tests that only cover the happy path, and over-mocking.

It ships as a single markdown file, SKILL.md, with the checklist and code blocks. Nothing runs, nothing to install beyond the skill itself. You add it through the plugin marketplace or npx skills add.

Scope is narrow on purpose: this one covers what to avoid. For positive patterns and architecture the author points to a separate python-design-patterns skill. Worth installing if you review Python regularly and want the agent checking more than syntax. For a throwaway script it is overkill.

What it helps with

  • spot timeout and retry logic duplicated across modules
  • move secrets and config out of source into environment variables
  • catch bare except Exception blocks that swallow failures
  • keep ORM models from leaking into API responses
  • add tests for error paths and edge cases

Example prompts for the agent

  • Review this file against the python-anti-patterns checklist and list the violations
  • Check services/orders.py for anti-patterns before I merge
  • Why does this batch job fail? Cross-check with python-anti-patterns

How to install python-anti-patterns

1Plugin marketplace

/plugin marketplace add wshobson/agents
/plugin install python-development@claude-code-workflows

This installs the whole python-development plugin with all its skills

2Skills CLI (Vercel)

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

3Manually: put the files in place

~/.claude/skills/python-anti-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/python-anti-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about python-anti-patterns

How do I install python-anti-patterns in Claude?

Use the plugin marketplace: /plugin marketplace add wshobson/agents, then /plugin install python-development@claude-code-workflows. Or run npx skills add wshobson/agents --skill python-anti-patterns -a claude-code.

What does python-anti-patterns do?

It gives the agent a checklist of common Python mistakes with bad and good code samples. The agent consults it during review, debugging, and before finalizing an implementation.

How is it different from python-design-patterns?

This skill covers what to avoid. For positive patterns and architecture, the author points to the python-design-patterns skill.

Source text

SKILL.md · MIT
---
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.

## 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-Pattern | Fix |
|-------------|-----|
| Scattered retry logic | Centralized decorators |
| Hard-coded config | Environment variables + pydantic-settings |
| Exposed ORM models | DTO/response schemas |
| Mixed I/O + logic | Repository pattern |
| Bare except | Catch specific exceptions |
| Batch stops on error | Return BatchResult with successes/failures |
| No validation | Validate at boundaries with Pydantic |
| Unclosed resources | Context managers |
| Blocking in async | Async-native libraries |
| Missing types | Type annotations on all public APIs |
| Only happy path tests | Test errors and edge cases |

© Seth Hobson · MIT · wshobson/agents

Similar skills

Everything for Code review and refactoring →
python-patterns affaan-m Tells the agent how to write and review Python: idioms, type hints, exception handling, context managers. CX Codex +1 5,500installs dataverse-python-advanced-patterns official github Guides GitHub Copilot to generate Dataverse Python code with error recovery, batch work, and OData query patterns. 9,213installs improve-codebase-architecture Matt Pocock This skill scans a codebase for architectural friction, then builds a visual HTML report with refactoring candidates. Use it before a deeper architecture review. 1,163,035installs tdd Matt Pocock Guides the red-green TDD loop: ensures tests are written first, keep them at public interfaces, and avoid coupling to implementation details. 1,141,062installs triage Matt Pocock This skill moves issues and external PRs through triage states, verification, and agent briefs. It fits maintainers managing an issue queue. 990,453installs codebase-design Matt Pocock This skill helps design modules with small interfaces and hidden complexity. Use it when refactoring code, choosing a seam, or making tests easier to write. 850,344installs code-review Matt Pocock Reviews changes from a chosen reference point against repository standards and the originating spec. Use it for a branch, PR, or work in progress. 789,521installs implement Matt Pocock Implements work from a specification or tickets, following a test-driven flow and ending with review and a commit. Use it when a coding task needs a defined delivery routine. 774,700installs

From the same set342

The whole set →
changelog-automation This skill helps generate changelogs and release notes from commits, PRs, and releases. Use it when setting up release workflows or shared commit rules. CX Codex 13,733installs visual-design-foundations This skill helps define typography, color, spacing, and icon rules for a project. Use it when setting up design tokens or bringing an interface into visual consistency. CX Codex 13,566installs debugging-strategies This skill gives an agent a step-by-step way to investigate bugs, crashes, and performance problems. Use it when a project behaves unexpectedly. CX Codex 13,414installs stripe-integration This skill covers Stripe Checkout, subscriptions, webhooks, refunds, and saved payment methods. Use it when a project needs one-time or recurring payments. CX Codex 13,404installs microservices-patterns A practical guide to service boundaries, event-driven communication, data ownership, and resilience patterns for distributed systems. CX Codex 13,176installs web-component-design This skill helps design reusable components for React, Vue, and Svelte. Use it for UI libraries, design systems, or legacy component refactors. CX Codex 13,167installs langchain-architecture This skill helps design LangChain 1.x and LangGraph applications with agents, memory, state, and tool calls. Use it for multi-step LLM workflows. CX Codex 13,150installs secrets-management This skill sets up secrets handling for CI/CD with Vault, AWS Secrets Manager, and platform stores. Use it for credentials, rotation, and protected deployments. CX Codex 13,122installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor