PYTHON · 함수
함수 어노테이션
함수 어노테이션으로 매개변수와 반환값의 타입을 명시하고, 런타임에서 검사하는 방법입니다.
함수중급annotation어노테이션typingCallable
핵심 설명
함수 어노테이션으로 매개변수와 반환값의 타입을 명시하고, 런타임에서 검사하는 방법입니다.
Python code
from typing import Callable, Any
import inspect
# 기본 어노테이션
def greet(name: str, times: int = 1) -> str:
return (f"안녕, {name}! " * times).strip()
# 어노테이션 접근
print(greet.__annotations__)
# {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
# 콜러블 타입
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
print(apply(lambda x, y: x + y, 3, 4)) # 7
# 런타임 타입 검사 데코레이터
def typecheck(func):
hints = func.__annotations__
sig = inspect.signature(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
for name, value in bound.arguments.items():
if name in hints and not isinstance(value, hints[name]):
raise TypeError(
f"{name}은(는) {hints[name].__name__}이어야 합니다"
)
return func(*args, **kwargs)
return wrapper
@typecheck
def add(a: int, b: int) -> int:
return a + b
print(add(1, 2)) # 3학습 팁
inspect.signature()로 함수의 매개변수 정보를 상세하게 조회할 수 있습니다.
주의할 점
Python의 타입 힌트는 기본적으로 런타임에 강제되지 않습니다. 런타임 검증이 필요하면 별도 도구(pydantic, beartype)를 사용하세요.
자주 묻는 질문
함수 어노테이션란 무엇인가요?
함수 어노테이션으로 매개변수와 반환값의 타입을 명시하고, 런타임에서 검사하는 방법입니다.
함수 어노테이션 학습 시 주의할 점은 무엇인가요?
Python의 타입 힌트는 기본적으로 런타임에 강제되지 않습니다. 런타임 검증이 필요하면 별도 도구(pydantic, beartype)를 사용하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.