python-typing-ops について
Python 開発者向けに、現代的で読みやすい型ヒントのパターンをまとめたスキルです。型チェッカーの実行方法や設定リソースも扱います。
主な機能
- 01関数とコレクションの型注釈
- 02Union、TypedDict、Callable 型
- 03ジェネリクス、Protocol、TypeGuard
- 04mypy と pyright の利用ガイド
- 05設定アセットと型チェック用スクリプト
活用シーン
- 01関数やデータ構造への型付け
- 02省略可能な値や固定キー辞書の表現
- 03ジェネリック型と構造的インターフェースの定義
- 04プロジェクト環境での型チェック
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill python-typing-opsインストール後、Claude Code で/python-typing-opsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/pyproject-typing.tomlreferences/generics-advanced.mdmypy-config.mdoverloads.mdprotocols-patterns.mdruntime-validation.mdtype-narrowing.mdscripts/check-types.sh詳細
Python の型付けパターン
安全でドキュメントが整った 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
コレクション
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 と Union
# 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
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
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:
...
ジェネリクス
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(構造的型付け)
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"{}"))
型ガード
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 と Final
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"
クイックリファレンス
| 型 | 用途 |
|---|---|
X | None | オプショナルな値 |
list[T] | 要素の型が統一されたリスト |
dict[K, V] | 辞書 |
Callable[[Args], Ret] | 関数の型 |
TypeVar("T") | ジェネリックパラメーター |
Protocol | 構造的型付け |
TypedDict | キーが固定された辞書 |
Literal["a", "b"] | 指定した値のみ |
Final | 再代入不可 |
型チェッカーのコマンド
# 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"
新登場:ty — Astral の Rust ベースの型チェッカーです(uv と ruff と同じツールチェーン)。mypy より大幅に高速です。現在はプレビュー版(1.0 未満)のため、引き続き mypy または pyright が本番環境での標準ですが、今後に注目する価値があり、簡単に試せます:uvx ty check。安定したら、新しいプロジェクトでの採用を検討してください。
追加リソース
./references/generics-advanced.md- TypeVar、ParamSpec、TypeVarTuple./references/protocols-patterns.md- 構造的型付け、実行時プロトコル./references/type-narrowing.md- ガード、isinstance、assert./references/mypy-config.md- mypy/pyright の設定./references/runtime-validation.md- Pydantic v2、typeguard、beartype./references/overloads.md- @overload デコレーターのパターン
スクリプト
./scripts/check-types.sh- 一般的なオプションで型チェッカーを実行します
アセット
./assets/pyproject-typing.toml- 推奨される mypy/pyright の設定
関連項目
これは前提条件のない基礎スキルです。
関連スキル:
python-pytest-ops- 型安全なフィクスチャとモック
このスキルを基に学ぶ:
python-async-ops- 非同期処理の型アノテーションpython-fastapi-ops- Pydantic モデルとバリデーションpython-database-ops- SQLAlchemy の型アノテーション
コメント
Markdown 対応