Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills Aโ€“Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Python Patterns

ASecurity

Use when Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.

5 stars
0 votes
0 copies
0 views
Added 9/27/2026
ai-agentspythongobashsqlfastapidjangoflasktestingapidatabase

Works with

terminalcliapi

Security Analysis

A100/100

Scanned 9/27/2026

$npx -y skills add Harmitx7/tribunal-kit --skill python-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Python Patterns?

Add the live security badge to your README โ€” it updates automatically with every re-scan.

Security grade badge for Python Patterns
[![Security: A โ€” Skills Directory](https://www.skillsdirectory.com/api/skills/harmitx7-python-patterns-tribunal-kit/badge)](https://www.skillsdirectory.com/skills/harmitx7-python-patterns-tribunal-kit)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: python-patterns
description: "Use when Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying."
version: 5.0.0
last-updated: 2026-09-13
skills:
  - python-pro
  - clean-code
  - data-validation-schemas
tools: Read, Grep, Glob, Bash, Edit, Write
scripts-binding:
  - .agent/scripts/lint_runner.js
  - .agent/scripts/verify_all.js
---

# Python Development Principles

---

## ๐Ÿ› ๏ธ Technical Architecture & Reference Recipes

---

## Hallucination Traps (Read First)

- โŒ Using `dict` for structured data when a dataclass/Pydantic model exists -> โœ… Dicts have no type safety; use typed models
- โŒ Catching bare `except:` or `except Exception:` -> โœ… Catch specific exceptions; bare except swallows KeyboardInterrupt and SystemExit
- โŒ Using `os.path` for path operations -> โœ… Use `pathlib.Path` for modern, readable path manipulation

---

---

## Framework Selection

| Use Case                     | Recommended    | When to Use                                  |
| ---------------------------- | -------------- | -------------------------------------------- |
| REST API, general-purpose    | FastAPI        | Type-safe, async, auto-docs via OpenAPI      |
| REST API, batteries-included | Django + DRF   | Rapid development, ORM included, admin panel |
| Microservice / minimal API   | Flask          | Simple, no overhead, full control            |
| Data pipeline / ETL          | No framework   | Standard library + pandas/polars as needed   |
| CLI tool                     | Click or Typer | Better than argparse for complex CLIs        |
| Async task queue             | Celery + Redis | Background jobs, scheduled tasks             |

**Decision question:** Does this need an ORM, admin panel, and auth out of the box? โ†’ Django. Does it need type-safe inputs with automatic validation? โ†’ FastAPI. Is it small and needs nothing? โ†’ Flask.

---

## Type Hints (Required on All New Code)

Python type hints are not optional โ€” they are documentation that also enables static analysis.

```python
# โŒ No type hints
def create_user(email, role):
    ...

# โœ… Typed
from typing import Literal

def create_user(email: str, role: Literal["admin", "user"] = "user") -> dict[str, str]:
    ...
```

**Rules:**

- All function parameters and return values must be typed
- Use `from __future__ import annotations` for forward references
- Run `mypy` or `pyright` as part of CI โ€” type errors fail the build

---

## Project Structure

```
src/
  api/          Route definitions (thin โ€” parse and delegate)
  services/     Business logic (no HTTP awareness)
  repositories/ Database access (no business logic)
  models/       Pydantic models + SQLAlchemy models
  lib/          Shared utilities
  config.py     Settings via pydantic-settings

tests/
  unit/         Isolated function tests
  integration/  Database and external service tests

pyproject.toml  โ€” single source of truth for deps, linting, test config
```

---

## Async Patterns

FastAPI uses async by default. Know when to use it and when not to.

```python
# โœ… Use async for I/O-bound operations
@app.get("/users/{user_id}")
async def get_user(user_id: str, db: AsyncSession = Depends(get_db)):
    return await user_service.find_by_id(db, user_id)

# โœ… Use sync for CPU-bound operations (or offload to thread pool)
import asyncio
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor()

@app.post("/process")
async def process_image(file: UploadFile):
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(executor, cpu_intensive_work, file)
    return result
```

**Never:** `time.sleep()` inside an async function โ€” use `await asyncio.sleep()` instead.

---

## Error Handling

```python
# Custom exception hierarchy
class AppError(Exception):
    def __init__(self, message: str, code: str, status_code: int = 400):
        self.message = message
        self.code = code
        self.status_code = status_code
        super().__init__(message)

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} {id} not found", "NOT_FOUND", 404)

class ValidationError(AppError):
    def __init__(self, message: str):
        super().__init__(message, "VALIDATION_FAILED", 400)

# FastAPI exception handler
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": exc.message, "code": exc.code}
    )
```

---

## Dependency Management

Use `pyproject.toml` with `uv` or `poetry`:

```toml
[project]
name = "my-service"
version = "0.1.0"
requires-python = ">=3.11"

dependencies = [
    "fastapi>=0.110",
    "pydantic>=2.0",
    "sqlalchemy[asyncio]>=2.0",
    "asyncpg>=0.29",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-asyncio>=0.23",
    "mypy>=1.0",
    "ruff>=0.3",
]
```

**Never use `requirements.txt` for production projects** โ€” no lock file, no version bounds, no dev/prod separation.

---

## Code Quality Tools

```bash
# Linting + formatting (replaces black + flake8 + isort)
ruff check . --fix
ruff format .

# Type checking
mypy src/

# Testing
pytest tests/ -v --tb=short

# Pre-commit (runs all of the above)
pre-commit run --all-files
```

Configure all tools in `pyproject.toml` โ€” not `.flake8`, `.mypy.ini`, and `.ruff.toml` separately.

---

## Output Format

When this skill produces or reviews code, structure your output as follows:

```
โ”โ”โ” Python Patterns Report โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
Skill:       Python Patterns
Language:    [detected language / framework]
Scope:       [N files ยท N functions]
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
โœ… Passed:   [checks that passed, or "All clean"]
โš ๏ธ  Warnings: [non-blocking issues, or "None"]
โŒ Blocked:  [blocking issues requiring fix, or "None"]
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
VBC status:  PENDING โ†’ VERIFIED
Evidence:    [test output / lint pass / compile success]
```

**VBC (Verification-Before-Completion) is mandatory.**
Do not mark status as VERIFIED until concrete terminal evidence is provided.

Attribution

Harmitx7Harmitx7
View sourceSee grades on GitHubMore from Harmitx7 โ†’
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698621 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents โ†’