아래는 Python의 typing 모듈 공식 문서에서 꼭 알아야 하는 핵심 개념 위주로 정리한 요약
def func(x: int, y: str) -> bool:
...
x: int, y: str: 인자 타입-> bool: 반환 타입| 타입 힌트 | 의미 | 예시 | |
|---|---|---|---|
Any | 어떤 타입이든 허용 | x: Any | |
Union[X, Y] | X 또는 Y 중 하나 | Union[int, str] | |
Optional[X] | X 또는 None (즉, `X | None`) | Optional[str] |
List[X] | X 타입의 리스트 | List[int] or list[int] | |
Dict[K, V] | 키: K, 값: V 타입의 딕셔너리 | Dict[str, int] | |
Tuple[X, Y] | 고정된 길이와 타입의 튜플 | Tuple[int, str] | |
Callable[[A], R] | 인자 A → 반환 R 함수 | Callable[[int], str] |
Vector = list[float]
def scale(v: Vector) -> Vector: ...
from typing import NewType
UserId = NewType("UserId", int)
UserId는 int와 런타임 동작은 같지만, 정적 타입 검사기에서 다른 타입으로 취급되어 논리 오류 방지에 유용from typing import TypeVar, Generic
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, content: T):
self.content = content
from collections.abc import Callable
f: Callable[[int, str], bool]
from typing import Annotated
x: Annotated[int, "metadata"]
from typing import Literal
def set_mode(mode: Literal["r", "w"]): ...
from typing import TypedDict
class User(TypedDict):
name: str
age: int
from typing import Protocol
class Speakable(Protocol):
def speak(self) -> str: ...
from typing import TypeGuard
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
Any: 타입 검사 무시 (탈출구)object: 모든 타입의 상위지만, 메서드 접근 제한 많음Self: 메서드가 self 자신을 반환할 때 사용 (Python 3.11+)Final: 재정의 금지ClassVar: 인스턴스가 아닌 클래스 변수임을 명시