home / skills / eyadsibai / ltk / python-patterns

This skill helps you write idiomatic modern Python by applying type hints, dataclasses, context managers, decorators, and async patterns.

npx playbooks add skill eyadsibai/ltk --skill python-patterns

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.1 KB
---
name: Python Patterns
description: This skill should be used when the user asks about "Python best practices", "Pythonic code", "Python patterns", "Python idioms", "type hints", "dataclasses", "async Python", "Python decorators", "context managers"
version: 1.0.0
---

# Python Patterns

Guidance for writing idiomatic, modern Python code.

## Modern Python Features (3.9+)

| Feature | Purpose | Key Concept |
|---------|---------|-------------|
| **Type hints** | Static analysis | `def func(x: str) -> int:` |
| **Dataclasses** | Structured data | Auto `__init__`, `__repr__`, etc. |
| **Context managers** | Resource cleanup | `with` statement guarantees cleanup |
| **Decorators** | Cross-cutting concerns | Wrap functions to add behavior |
| **Async/await** | Concurrent I/O | Non-blocking operations |

---

## Type Hints

**Modern syntax (3.10+)**: Use `|` for unions, built-in types for generics.

| Old | Modern |
|-----|--------|
| `Optional[str]` | `str \| None` |
| `Union[str, int]` | `str \| int` |
| `List[str]` | `list[str]` |
| `Dict[str, int]` | `dict[str, int]` |

**Key concept**: Type hints are for tooling (mypy, IDEs) - no runtime enforcement.

---

## Dataclasses vs Alternatives

| Use | For |
|-----|-----|
| `@dataclass` | Mutable data with methods |
| `@dataclass(frozen=True)` | Immutable, hashable |
| `NamedTuple` | Lightweight, tuple semantics |
| `TypedDict` | Dict with known keys |
| `Pydantic` | Validation, serialization |

---

## Context Managers

Use for any resource that needs cleanup: files, connections, locks, transactions.

**Pattern**: Acquire in `__enter__`, release in `__exit__` (or use `@contextmanager` with `yield`)

---

## Decorators

| Pattern | Use Case |
|---------|----------|
| Simple decorator | Logging, timing |
| Decorator with args | Configurable behavior |
| Class decorator | Modify class definition |
| `@functools.wraps` | Preserve function metadata |

---

## Async Python

**When to use**: I/O-bound operations (HTTP requests, DB queries, file I/O)

**When NOT to use**: CPU-bound operations (use `multiprocessing` instead)

| Concept | Purpose |
|---------|---------|
| `async def` | Define coroutine |
| `await` | Suspend until complete |
| `asyncio.gather()` | Run multiple concurrently |
| `async with` | Async context manager |
| `async for` | Async iteration |

---

## Pythonic Idioms

| Instead of | Use |
|------------|-----|
| `if len(x) > 0:` | `if x:` |
| `for i in range(len(x)):` | `for item in x:` or `enumerate()` |
| `d.has_key(k)` | `k in d` |
| `try/if exists` (LBYL) | `try/except` (EAFP) |
| Manual swap | `a, b = b, a` |

---

## Project Structure

```
my_project/
├── src/my_package/     # Source code
├── tests/              # Test files
├── pyproject.toml      # Project config
└── README.md
```

**Key concept**: Use `src/` layout to prevent import confusion.

---

## Tooling

| Tool | Purpose |
|------|---------|
| **ruff** | Fast linter + formatter |
| **mypy** | Type checking |
| **pytest** | Testing |
| **uv/pip** | Dependencies |

## Resources

- Python docs: <https://docs.python.org/3/>
- Real Python: <https://realpython.com/>

Overview

This skill provides concise guidance for writing idiomatic, modern Python code focused on patterns, best practices, and practical features (3.9+). It covers type hints, dataclasses, context managers, decorators, async/await, Pythonic idioms, project layout, and recommended tooling. The goal is to help you write clearer, safer, and more maintainable Python.

How this skill works

The skill inspects common Python concerns and recommends modern constructs and patterns to solve them. It explains when to use type hints and dataclasses, how to implement context managers and decorators correctly, and when to prefer async code versus multiprocessing. It also highlights small idioms and project layout choices that reduce bugs and improve readability.

When to use it

  • When you want to add static typing and improve IDE/mypy support
  • When modeling structured data or simple DTOs (use dataclasses or TypedDict)
  • When managing resources that require deterministic cleanup (files, locks, DB transactions)
  • When implementing cross-cutting logic like logging or timing (use decorators)
  • When handling high-concurrency I/O tasks (use async/await and asyncio)
  • When setting up a new project layout and toolchain (use src/ layout, ruff, mypy, pytest)

Best practices

  • Prefer modern type hint syntax (PEP 604 and built-in generics: list[str], dict[str, int]) for clearer typing
  • Use @dataclass for mutable structured data and @dataclass(frozen=True) for immutable records
  • Use context managers (with / async with) for resource lifecycle to guarantee cleanup
  • Write small, well-documented decorators and use functools.wraps to preserve metadata
  • Choose async only for I/O-bound concurrency; use multiprocessing for CPU-bound work
  • Adopt src/ project layout and a toolchain (ruff for linting, mypy for types, pytest for tests)

Example use cases

  • Add type hints to a library to improve IDE completion and enable mypy checks
  • Replace a plain class with a dataclass to reduce boilerplate and get repr/equality for free
  • Wrap database transactions in a context manager to ensure rollback on errors
  • Implement a timing decorator to measure function latency while preserving metadata
  • Refactor blocking HTTP calls to async coroutines to handle many concurrent requests efficiently

FAQ

Are type hints enforced at runtime?

No. Type hints are for tooling and documentation; use runtime checks or libraries like pydantic if you need validation.

When should I choose dataclasses over NamedTuple or TypedDict?

Use dataclasses for mutable records with methods, frozen dataclasses for immutability, NamedTuple for lightweight tuple semantics, and TypedDict for dict-like shapes.