Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

python-typing-ops

/python-typing-ops

Stosuje wzorce adnotacji typów w Python: TypeVar, Generic, Protocol, overload i TypedDict oraz sprawdzanie przez mypy i pyright.

Repozytorium
claude-mods ↗
Licencja
MIT
Ostatnia zmiana repozytorium
15.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
9
Skrypty
1
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 15.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co sprawdzić przed instalacją
  • 1 skrypt w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.

Skrypty: scripts/check-types.sh

Co robi i kiedy

Stosuje wzorce adnotacji typów w Python: TypeVar, Generic, Protocol, overload i TypedDict oraz sprawdzanie przez mypy i pyright.

Oryginalny opis (EN)

Python type hints and type safety patterns. Triggers on: type hints, typing, TypeVar, Generic, Protocol, mypy, pyright, type annotation, overload, TypedDict.

Jak działa

  1. Basic Annotations
  2. Collections
  3. Optional and Union
  4. TypedDict
  5. Callable
  6. Generics
  7. Protocol (Structural Typing)
  8. Type Guards
  9. Literal and Final
  10. Quick Reference
Sekcje z nagłówków SKILL.md, w oryginale · 230 linii, 693 słów
Podgląd SKILL.md
---
name: python-typing-ops
description: "Python type hints and type safety patterns. Triggers on: type hints, typing, TypeVar, Generic, Protocol, mypy, pyright, type annotation, overload, TypedDict."
license: MIT
compatibility: "Python 3.10+ (uses union syntax X | Y). Some patterns require 3.11+ (Self, TypeVarTuple)."
allowed-tools: "Read Write"
metadata:
  author: claude-mods
  related-skills: python-pytest-ops
---

# Python Typing Patterns

Modern type hints for safe, documented Python code.

## Basic Annotations

```python
# Variables
name: str = "Alice"
count: int = 42
items: list[str] = ["a", "b"]
mapping: dict[str, int] = {"key": 1}

# Function signatures
def greet(name: str, times: int = 1) -> str:
    return f"Hello, {name}!" * times

# None handling
def find(id: int) -> str | None:
    return db.get(id)  # May return None
```

## Collections

```python
from collections.abc import Sequence, Mapping, Iterable

# Use collection ABCs for flexibility
def process(items: Sequence[str]) -> list[str]:
    """Accepts list, tuple, or any sequence."""
    return [item.upper() for item in items]

def lookup(data: Mapping[str, int], key: str) -> int:
    """Accepts dict or any mapping."""
    return data.get(key, 0)

# Nested types
Matrix = list[list[float]]
Config = dict[str, str | int | bool]
```

## Optional and Union

```python
# Modern syntax (3.10+)
def find(id: int) -> User | None:
    pass

def parse(value: str | int | float) -> str:
    pass

# With default None
def fetch(url: str, timeout: float | None = None) -> bytes:
    pass
```

## TypedDict

```python
from typing import TypedDict, Required, NotRequired

class UserDict(TypedDict):
    id: int
    name: str
    email: str | None

class ConfigDict(TypedDict, total=False):  # All optional
    debug: bool
    log_level: str

class APIResponse(TypedDict):
    data: Required[list[dict]]
    error: NotRequired[str]

def process_user(user: UserDict) -> str:
    return user["name"]  # Type-safe key access
```

## Callable

```python
from collections.abc import Callable

# Function type
Handler = Callable[[str, int], bool]

def register(callback: Callable[[str], None]) -> None:
    pass

# With keyword args (use Protocol instead)
from typing import Protocol

class Processor(Protocol):
    def __call__(self, data: str, *, verbose: bool = False) -> int:
        ...
```

## Generics

```python
from typing import TypeVar

T = TypeVar("T")

def first(items: list[T]) -> T | None:
    return items[0] if items else None

# Bounded TypeVar
from typing import SupportsFloat

N = TypeVar("N", bound=SupportsFloat)

def average(values: list[N]) -> float:
    return sum(float(v) for v in values) / len(values)
```

## Protocol (Structural Typing)

```python
from typing import Protocol

class Readable(Protocol):
    def read(self, n: int = -1) -> bytes:
        ...

def load(source: Readable) -> dict:
    """Accepts any object with read() method."""
    data = source.read()
    return json.loads(data)

# Works with file, BytesIO, custom classes
load(open("data.json", "rb"))
load(io.BytesIO(b"{}"))
```

## Type Guards

```python
from typing import TypeGuard

def is_string_list(val: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)

def process(items: list[object]) -> None:
    if is_string_list(items):
        # items is now list[str]
        print(", ".join(items))
```

## Literal and Final

```python
from typing import Literal, Final

Mode = Literal["read", "write", "append"]

def open_file(path: str, mode: Mode) -> None:
    pass

# Constants
MAX_SIZE: Final = 1024
API_VERSION: Final[str] = "v2"
```

## Quick Reference

| Type | Use Case |
|------|----------|
| `X \| None` | Optional value |
| `list[T]` | Homogeneous list |
| `dict[K, V]` | Dictionary |
| `Callable[[Args], Ret]` | Function type |
| `TypeVar("T")` | Generic parameter |
| `Protocol` | Structural typing |
| `TypedDict` | Dict with fixed keys |
| `Literal["a", "b"]` | Specific values only |
| `Final` | Cannot be reassigned |

## Type Checker Commands

```bash
# mypy (run inside the project env)
uv run mypy src/ --strict

# pyright
uv run pyright src/

# In pyproject.toml
[tool.mypy]
strict = true
python_version = "3.11"
```

**Emerging: `ty`** — Astral's Rust-based type checker (same toolchain as uv +
ruff), dramatically faster than mypy. Still in preview (pre-1.0), so mypy or
pyright remain the production default — but worth watching, and easy to try:
`uvx ty check`. Adopt for new projects once it stabilizes.

## Additional Resources

- `./references/generics-advanced.md` - TypeVar, ParamSpec, TypeVarTuple
- `./references/protocols-patterns.md` - Structural typing, runtime protocols
- `./references/type-narrowing.md` - Guards, isinstance, assert
- `./references/mypy-config.md` - mypy/pyright configuration
- `./references/runtime-validation.md` - Pydantic v2, typeguard, beartype
- `./references/overloads.md` - @overload decorator patterns

## Scripts

- `./scripts/check-types.sh` - Run type checkers with common options

## Assets

- `./assets/pyproject-typing.toml` - Recommended mypy/pyright config

---

## See Also

This is a **foundation skill** with no prerequisites.

**Related Skills:**
- `python-pytest-ops` - Type-safe fixtures and mocking

**Build on this skill:**
- `python-async-ops` - Async type annotations
- `python-fastapi-ops` - Pydantic models and validation
- `python-database-ops` - SQLAlchemy type annotations
Pliki w paczce (9)
  • SKILL.md 5 KB
  • assets/pyproject-typing.toml 3 KB
  • references/generics-advanced.md 6 KB
  • references/mypy-config.md 6 KB
  • references/overloads.md 6 KB
  • references/protocols-patterns.md 6 KB
  • references/runtime-validation.md 7 KB
  • references/type-narrowing.md 6 KB
  • scripts/check-types.sh 3 KB

Wersje

W bazie nie ma innych skilli o nazwie python-typing-ops.

Migawka bazy z 13.11.2026 · wersja paczki d9f6721d0cbc (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 95python-type-system
    Pomaga w systemie typów Pythona: type hints, mypy, Protocol, TypedDict i Generics oraz w adnotacjach typów.
  • 90vibe-types:python
    Podpowiada sposoby typowania w Pythonie: adnotacje, TypedDict, Protocol, generyki i naprawę błędów mypy oraz pyright.
  • 100python-type-safety
    Dodaje adnotacje typów w Pythonie, generyki, protokoły i ścisłe sprawdzanie typów w mypy lub pyright.
  • 100python-type-safety
    Zapewnia bezpieczeństwo typów w Python: adnotacje, generyki, protokoły i ścisłe sprawdzanie typów, w tym konfiguracja mypy i pyright.
  • 95python-type-safety
    Dodaje bezpieczne typowanie w Pythonie: generyki, protokoły i ścisłe sprawdzanie typów przez ty i ruff.
  • 90python-language-contracts-typing
    Statycznie przegląda kontrakty typów w Pythonie: propagację Any, Protocol, generyki i wariancję, spójność overloadów, TypedDict i dataclasses oraz rozdział typowania statycznego od walidacji w czasie działania.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.