P

Python Patterns System

Battle-tested skill for python, development, principles, decision. Includes structured workflows, validation checks, and reusable patterns for development.

SkillClipticsdevelopmentv1.0.0MIT
0 views0 copies

Python Development Patterns Skill

A Claude Code skill for writing production-quality Python — covering idiomatic patterns, type hints, async programming, testing strategies, project structure, and performance optimization.

When to Use This Skill

Choose this skill when:

  • Writing Python code following modern best practices (3.10+)
  • Implementing async patterns with asyncio
  • Structuring Python projects for maintainability
  • Adding type hints and runtime validation
  • Optimizing Python performance
  • Writing tests with pytest

Consider alternatives when:

  • You need Django or Flask-specific guidance (use framework skills)
  • You need data science patterns (use a data science skill)
  • You need machine learning (use a ML/AI skill)

Quick Start

# Set up a Python project python -m venv .venv source .venv/bin/activate pip install ruff mypy pytest
# Modern Python patterns (3.10+) from dataclasses import dataclass, field from typing import TypeAlias # Type aliases for clarity UserId: TypeAlias = str Email: TypeAlias = str @dataclass class User: id: UserId name: str email: Email tags: list[str] = field(default_factory=list) def is_admin(self) -> bool: return "admin" in self.tags # Pattern matching (3.10+) def handle_response(status: int) -> str: match status: case 200: return "OK" case 404: return "Not Found" case 500: return "Server Error" case _: return f"Unknown: {status}"

Core Concepts

Python Idioms

PatternPythonicNot Pythonic
List comprehension[x*2 for x in items]map(lambda x: x*2, items)
Dictionary building{k: v for k, v in pairs}Manual loop with d[k] = v
Context managerwith open(f) as fp:fp = open(f); fp.close()
Unpackinga, b, *rest = itemsa = items[0]; b = items[1]
Truthinessif items:if len(items) > 0:
EAFPtry: x[key]if key in x: x[key]

Async Patterns

import asyncio from aiohttp import ClientSession async def fetch_all(urls: list[str]) -> list[dict]: async with ClientSession() as session: tasks = [fetch_one(session, url) for url in urls] return await asyncio.gather(*tasks) async def fetch_one(session: ClientSession, url: str) -> dict: async with session.get(url) as response: return await response.json() # Run async code results = asyncio.run(fetch_all(["https://api.example.com/1", "https://api.example.com/2"]))

Project Structure

myproject/
ā”œā”€ā”€ src/myproject/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ models.py        # Data models
│   ā”œā”€ā”€ services.py      # Business logic
│   ā”œā”€ā”€ api.py           # API endpoints
│   └── utils.py         # Utilities
ā”œā”€ā”€ tests/
│   ā”œā”€ā”€ conftest.py      # Shared fixtures
│   ā”œā”€ā”€ test_models.py
│   └── test_services.py
ā”œā”€ā”€ pyproject.toml        # Project config
ā”œā”€ā”€ .python-version       # Python version
└── ruff.toml             # Linter config

Configuration

ParameterTypeDefaultDescription
python_versionstring"3.12"Minimum Python version
type_checkerstring"mypy"Type checker: mypy, pyright
linterstring"ruff"Linter: ruff, flake8, pylint
formatterstring"ruff"Formatter: ruff, black
test_frameworkstring"pytest"Test framework: pytest, unittest
async_frameworkstring"asyncio"Async: asyncio, trio
package_managerstring"pip"Package manager: pip, uv, poetry

Best Practices

  1. Use type hints on all public functions — type hints serve as documentation and enable static analysis; use mypy --strict or pyright to catch type errors before runtime.

  2. Prefer dataclass or pydantic.BaseModel over plain dicts — structured data types provide validation, IDE autocompletion, and self-documenting code; dicts are error-prone and hard to refactor.

  3. Use ruff for both linting and formatting — ruff is 10-100x faster than flake8 + black combined and covers both linting and formatting in a single tool.

  4. Write fixtures in conftest.py for shared test setup — pytest fixtures provide dependency injection for tests; shared fixtures in conftest.py are auto-discovered by all tests in the directory.

  5. Use asyncio.gather for concurrent I/O operations — when making multiple HTTP requests or database queries, gather them for concurrent execution instead of awaiting sequentially.

Common Issues

Circular imports between modules — Two modules importing each other causes ImportError. Break the cycle by moving shared types to a separate types.py module or using TYPE_CHECKING guard for type-only imports.

asyncio.run() fails with "event loop already running" — This happens inside Jupyter notebooks or frameworks that already have an event loop. Use await directly or nest_asyncio.apply() as a workaround.

Type checker reports false positives on library code — Some libraries lack type stubs. Install types-* packages from PyPI (e.g., types-requests) or add # type: ignore[import] for untyped libraries.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates