jpskill.com
🛠️ 開発・MCP コミュニティ

python-typing-patterns

Pythonの型ヒントや型安全性のパターンを理解し、mypyなどのツールでコードの品質を高めるSkill。

📜 元の英語説明(参考)

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

🇯🇵 日本人クリエイター向け解説

一言でいうと

Pythonの型ヒントや型安全性のパターンを理解し、mypyなどのツールでコードの品質を高めるSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

[Skill 名] python-typing-patterns

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:
        ...

Generics

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"{}"))

Type Guards

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
mypy src/ --strict

# pyright
pyright src/

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

その他のリソース

  • ./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-patterns - 型安全なフィクスチャとモック

このスキルを基盤とするスキル:

  • python-async-patterns - 非同期型アノテーション
  • python-fastapi-patterns - Pydanticモデルとバリデーション
  • python-database-patterns - SQLAlchemy型アノテーション
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Python Typing Patterns

Modern type hints for safe, documented Python code.

Basic Annotations

# 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

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

# 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:
        ...

Generics

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)

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

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

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

# mypy
mypy src/ --strict

# pyright
pyright src/

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

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-patterns - Type-safe fixtures and mocking

Build on this skill:

  • python-async-patterns - Async type annotations
  • python-fastapi-patterns - Pydantic models and validation
  • python-database-patterns - SQLAlchemy type annotations