본문으로 건너뛰기
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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-type-safety/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 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

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬