PHpullh
학습 라이브러리/Python/typing 모듈 & Protocol 고급

PYTHON · 성능

typing 모듈 & Protocol 고급

타입 힌트로 코드 품질과 IDE 지원을 극대화합니다.

성능중급typingOptionalUnionGenericTypeVar

핵심 설명

타입 힌트로 코드 품질과 IDE 지원을 극대화합니다.

Python code

from typing import (
    Optional, Union, List, Dict, Tuple,
    TypeVar, Generic, Callable, TypeAlias
)
from collections.abc import Iterator, Generator

# Optional (= X | None)
def find_user(id: int) -> Optional[str]:
    return "Alice" if id == 1 else None

# Union (Python 3.10+: X | Y)
def process(value: int | str | None) -> str:
    match value:
        case int():  return f"정수: {value}"
        case str():  return f"문자열: {value}"
        case None:   return "없음"

# TypeVar — 제네릭
T = TypeVar("T")

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

# Generic 클래스
class Stack(Generic[T]):
    def __init__(self): self._data: List[T] = []
    def push(self, item: T) -> None: self._data.append(item)
    def pop(self) -> T: return self._data.pop()

# TypeAlias (Python 3.10+)
UserID: TypeAlias = int
Matrix: TypeAlias = List[List[float]]

# Callable
Transform = Callable[[int], int]

def apply(fn: Transform, value: int) -> int:
    return fn(value)

# Generator 타입 힌트
def count_up(n: int) -> Generator[int, None, None]:
    for i in range(n): yield i

s: Stack[str] = Stack()
s.push("hello")
print(s.pop())   # hello

학습 팁

Python 3.10+에서는 Optional[X] 대신 X | None, Union[X, Y] 대신 X | Y를 쓸 수 있습니다. 훨씬 간결합니다.

주의할 점

타입 힌트는 런타임에 강제되지 않습니다. mypy, pyright, ruff 같은 정적 분석 도구와 함께 사용해야 효과가 있습니다.

자주 묻는 질문

typing 모듈 & Protocol 고급란 무엇인가요?

타입 힌트로 코드 품질과 IDE 지원을 극대화합니다.

typing 모듈 & Protocol 고급 학습 시 주의할 점은 무엇인가요?

타입 힌트는 런타임에 강제되지 않습니다. mypy , pyright , ruff 같은 정적 분석 도구와 함께 사용해야 효과가 있습니다.