한양과학기술고등학교

에듀테크 프로젝트 대시보드

타입 힌트

typing Optional list[int] Callable mypy

런타임에는 강제되지 않지만, 에디터 자동완성·정적 분석(mypy·pyright)·문서화에 큰 도움이 됩니다.

1. 기본 표기

def greet(name: str, times: int = 1) -> str:
    return f"hi {name}" * times

age: int = 20
scores: list[int] = []
config: dict[str, str] = {}
point: tuple[float, float] = (1.0, 2.0)

2. Optional 과 Union

def find(id: int) -> str | None:      # 3.10+ 권장 표기
    ...

from typing import Optional, Union
def find(id: int) -> Optional[str]:   # == str | None
    ...

value: int | str = 0                  # 둘 중 하나

3. 컬렉션·콜러블

from typing import Callable, Iterable, Iterator, Any

handler: Callable[[int, str], bool]   # (int, str) -> bool
items: Iterable[int]
def gen() -> Iterator[int]: ...

def process(data: list[dict[str, Any]]) -> None: ...

from collections.abc import Sequence   # 더 넓은 추상 타입
def first(seq: Sequence[int]) -> int:
    return seq[0]

4. 타입 별칭 · TypedDict · 제네릭

type Vector = list[float]            # 3.12+ 별칭 문법
Matrix = list[list[float]]           # 그 이전

from typing import TypedDict
class User(TypedDict):
    name: str
    age: int
u: User = {"name": "김", "age": 20}

def first[T](items: list[T]) -> T:   # 3.12+ 제네릭 함수
    return items[0]

5. 클래스와 힌트

class Stack:
    def __init__(self) -> None:
        self._items: list[int] = []

    def push(self, x: int) -> None:
        self._items.append(x)

    def pop(self) -> int:
        return self._items.pop()

# 자기 클래스 참조는 문자열 또는 from __future__ import annotations
def clone(self) -> "Stack": ...

6. 런타임 확인·도구

# 힌트는 강제되지 않음 — 이 호출도 실행됨
greet(123)          # mypy 는 경고, 파이썬은 실행

import typing
typing.get_type_hints(greet)   # 힌트를 dict 로

# 검사 도구
#   pip install mypy && mypy myfile.py
#   pyright / ruff 도 타입 체크 지원
실전 팁
  • 공개 API·함수 시그니처부터 붙이기. 지역 변수는 대개 생략 가능
  • from __future__ import annotations — 모든 힌트를 문자열로 지연 평가
  • 과한 Any 는 타입 체크를 무력화 — 정말 모를 때만
"가독성은 중요하다 (Readability counts)"