本文へスキップ
Skillpedia
一般的なプログラミング41k · #6769

python-type-safety

できること

より信頼性の高いPythonコードを書く手助けをします。「型ヒント」を使うことで、プログラムを実行する前に、データが正しく使われているかをコンピューターがチェックできるようにします。

使う場面

  • ✓既存のコードに型チェックを追加するとき。
  • ✓異なるデータ型でも使えるコード部分を作るとき。
  • ✓Pythonコードを自動でチェックするツールを設定するとき。

スキルのリンク

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-type-safety/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-type-safety/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“関数が必ず整数を受け取るようにするには、どうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

コードに「ラベル」(型アノテーション)を付けて、各部分がどのデータ型であるべきかを示します。mypyやpyrightなどのツールがそのラベルを読み取り、問題があれば警告してくれます。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

Python Type Safety

Leverage Python's type system to catch errors at static analysis time. Type annotations serve as enforced documentation that tooling validates automatically.

When to Use This Skill

  • Adding type hints to existing code
  • Creating generic, reusable classes
  • Defining structural interfaces with protocols
  • Configuring mypy or pyright for strict checking
  • Understanding type narrowing and guards
  • Building type-safe APIs and libraries

Core Concepts

1. Type Annotations

Declare expected types for function parameters, return values, and variables.

2. Generics

Write reusable code that preserves type information across different types.

3. Protocols

Define structural interfaces without inheritance (duck typing with type safety).

4. Type Narrowing

Use guards and conditionals to narrow types within code blocks.

Quick Start

def get_user(user_id: str) -> User | None:
    """Return type makes 'might not exist' explicit."""
    ...

# Type checker enforces handling None case
user = get_user("123")
if user is None:
    raise UserNotFoundError("123")
print(user.name)  # Type checker knows user is User here

Fundamental Patterns

Pattern 1: Annotate All Public Signatures

Every public function, method, and class should have type annotations.

def get_user(user_id: str) -> User:
    """Retrieve user by ID."""
    ...

def process_batch(
    items: list[Item],
    max_workers: int = 4,
) -> BatchResult[ProcessedItem]:
    """Process items concurrently."""
    ...

class UserRepository:
    def __init__(self, db: Database) -> None:
        self._db = db

    async def find_by_id(self, user_id: str) -> User | None:
        """Return User if found, None otherwise."""
        ...

    async def find_by_email(self, email: str) -> User | None:
        ...

    async def save(self, user: User) -> User:
        """Save and return user with generated ID."""
        ...

Use mypy --strict or pyright in CI to catch type errors early. For existing projects, enable strict mode incrementally using per-module overrides.

Pattern 2: Use Modern Union Syntax

Python 3.10+ provides cleaner union syntax.

# Preferred (3.10+)
def find_user(user_id: str) -> User | None:
    ...

def parse_value(v: str) -> int | float | str:
    ...

# Older style (still valid, needed for 3.9)
from typing import Optional, Union

def find_user(user_id: str) -> Optional[User]:
    ...

Pattern 3: Type Narrowing with Guards

Use conditionals to narrow types for the type checker.

def process_user(user_id: str) -> UserData:
    user = find_user(user_id)

    if user is None:
        raise UserNotFoundError(f"User {user_id} not found")

    # Type checker knows user is User here, not User | None
    return UserData(
        name=user.name,
        email=user.email,
    )

def process_items(items: list[Item | None]) -> list[ProcessedItem]:
    # Filter and narrow types
    valid_items = [item for item in items if item is not None]
    # valid_items is now list[Item]
    return [process(item) for item in valid_items]

Pattern 4: Generic Classes

Create type-safe reusable containers.

from typing import TypeVar, Generic

T = TypeVar("T")
E = TypeVar("E", bound=Exception)

class Result(Generic[T, E]):
    """Represents either a success value or an error."""

    def __init__(
        self,
        value: T | None = None,
        error: E | None = None,
    ) -> None:
        if (value is None) == (error is None):
            raise ValueError("Exactly one of value or error must be set")
        self._value = value
        self._error = error

    @property
    def is_success(self) -> bool:
        return self._error is None

    @property
    def is_failure(self) -> bool:
        return self._error is not None

    def unwrap(self) -> T:
        """Get value or raise the error."""
        if self._error is not None:
            raise self._error
        return self._value  # type: ignore[return-value]

    def unwrap_or(self, default: T) -> T:
        """Get value or return default."""
        if self._error is not None:
            return default
        return self._value  # type: ignore[return-value]

# Usage preserves types
def parse_config(path: str) -> Result[Config, ConfigError]:
    try:
        return Result(value=Config.from_file(path))
    except ConfigError as e:
        return Result(error=e)


…
よくある質問

「型ヒント」とは何ですか?

コードに付ける、想定されるデータ型(文字列、整数、小数など)を示すラベルのようなものです。コンピューターがコードを理解し、チェックするのに役立ちます。

Pythonは柔軟なのに、なぜこれを使うのですか?

Pythonの柔軟さは、見つけにくいエラーを招くことがあります。型ヒントを使うと、こうしたエラーを早い段階で発見でき、コードをより堅牢で保守しやすくできます。

すべてのコードを書き換える必要がありますか?

必ずしもそうではありません。他の人が使う関数など、重要な部分から型ヒントを少しずつ追加していけます。

詳細

作者による元の説明

Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.

repo: wshobson/agents

人気

GitHubのスター
41k
ランキング
#6769
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル