typing hint

Leejaegun·2025년 7월 6일

코딩테스트 시리즈

목록 보기
39/49

아래는 Python의 typing 모듈 공식 문서에서 꼭 알아야 하는 핵심 개념 위주로 정리한 요약


✅ 1. 기본 타입 힌트 구문

def func(x: int, y: str) -> bool:
    ...
  • x: int, y: str: 인자 타입
  • -> bool: 반환 타입

✅ 2. 자주 쓰는 타입들

타입 힌트의미예시
Any어떤 타입이든 허용x: Any
Union[X, Y]X 또는 Y 중 하나Union[int, str]
Optional[X]X 또는 None (즉, `XNone`)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]

✅ 3. 고급 타입 힌트

🔹 Type Alias

Vector = list[float]
def scale(v: Vector) -> Vector: ...

🔹 NewType

from typing import NewType
UserId = NewType("UserId", int)
  • UserIdint와 런타임 동작은 같지만, 정적 타입 검사기에서 다른 타입으로 취급되어 논리 오류 방지에 유용

✅ 4. 제네릭 (Generic)

from typing import TypeVar, Generic

T = TypeVar("T")

class Box(Generic[T]):
    def __init__(self, content: T):
        self.content = content
  • 타입 파라미터로 클래스나 함수 일반화

✅ 5. Callable (함수 타입)

from collections.abc import Callable

f: Callable[[int, str], bool]
  • int, str 인자를 받고 bool을 반환하는 함수

✅ 6. Annotated

from typing import Annotated

x: Annotated[int, "metadata"]
  • 타입에 메타데이터를 추가할 수 있는 구조
  • 정적 검사기가 무시할 수도 있고, 특정 라이브러리는 해석해서 사용 가능

✅ 7. Literal

from typing import Literal

def set_mode(mode: Literal["r", "w"]): ...
  • 특정 리터럴 값만 허용하도록 제한

✅ 8. TypedDict

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int
  • 타입이 지정된 dict 구조
  • 필드 누락 방지에 유용함

✅ 9. Protocol (구조적 서브타이핑 / 인터페이스)

from typing import Protocol

class Speakable(Protocol):
    def speak(self) -> str: ...
  • 클래스에 명시적으로 상속하지 않아도, 같은 메서드가 있으면 OK (Duck Typing)

✅ 10. TypeGuard / TypeIs

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: 인스턴스가 아닌 클래스 변수임을 명시
profile
Lee_AA

0개의 댓글