Python 24일 코스 - Day 22: 타입 힌트

Day 22: 타입 힌트

기본 타입 힌트

def greet(name: str) -> str:
    return f"안녕하세요, {name}님!"

age: int = 25
price: float = 19.99
is_active: bool = True

컬렉션 타입

# Python 3.9+
def average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

def get_user_info() -> dict[str, str]:
    return {"name": "철수", "email": "cs@example.com"}

coordinates: tuple[float, float] = (37.5665, 126.9780)
unique_ids: set[int] = {1, 2, 3}

Optional과 Union

from typing import Optional

def find_user(user_id: int) -> Optional[dict]:
    """사용자를 찾지 못하면 None을 반환합니다."""
    users = {1: {"name": "철수"}, 2: {"name": "영희"}}
    return users.get(user_id)

# Python 3.10+ Union 문법
def process(value: int | str) -> str:
    return str(value)

TypedDict

from typing import TypedDict

class UserProfile(TypedDict):
    name: str
    age: int
    email: str

def display_profile(user: UserProfile) -> None:
    print(f"{user['name']} ({user['age']}세)")

profile: UserProfile = {
    "name": "철수",
    "age": 25,
    "email": "cs@example.com"
}

제네릭과 Callable

from typing import Callable, TypeVar

T = TypeVar("T")

def first_element(items: list[T]) -> T:
    return items[0]

result_int = first_element([1, 2, 3])      # T는 int
result_str = first_element(["a", "b"])      # T는 str

def apply_func(func: Callable[[int], int], value: int) -> int:
    return func(value)

print(apply_func(lambda x: x * 2, 5))  # 10

mypy로 타입 검사

pip install mypy
mypy my_script.py
# mypy가 오류를 잡아냅니다
def add(a: int, b: int) -> int:
    return a + b

result = add("hello", "world")  # mypy 에러!

오늘의 연습문제

  1. 기존에 작성한 함수 3개에 타입 힌트를 추가하고 mypy로 검증하세요.
  2. TypedDict로 API 응답 구조를 정의하고 활용하는 코드를 작성하세요.
  3. 제네릭 Stack[T] 클래스를 타입 힌트와 함께 구현하세요.

이 글이 도움이 되었나요?