[Fluent Python : Ch. 8] Type Annotation + beartype (260614)

WonTerry·2026년 6월 14일

Python

목록 보기
14/20

파이썬에서 "어노테이트(annotate)한다"는 말은 코드에 추가적인 정보를 붙여주는 것을 의미한다. 프로그램의 실행에 직접적인 영향을 주기보다는 사람이나 개발 도구(IDE, 타입 체커 등)가 코드를 더 잘 이해하도록 돕기 위한 메타데이터이다.

# 어노테이션은 파이썬 인터프리터가 사용하는 정보가 아니라 개발자를 위한 정보
# 함수에서도 사용가능

def add(a: int, b: int) -> int:
    return a + b

# add 함수는 int 두 개를 받아서 int를 반환한다.

add("a", "b")  # 문자열을 넣어도 일단 실행은 된다.

# 출력결과 : ab

beartype

# 실행 시 타입을 강제하는 방법
# beartype, typeguard

from beartype import beartype

@beartype
def add(a: int, b: int) -> int:
    return a + b

에러 메세지

---------------------------------------------------------------------------
BeartypeCallHintParamViolation            Traceback (most recent call last)
Cell In[9], line 1
----> 1 add("a", "b")

File <@beartype(__main__.add) at 0x10d00e820>:28, in add(__beartype_get_violation, __beartype_conf, __beartype_check_meta, __beartype_func, *args, **kwargs)

BeartypeCallHintParamViolation: Function __main__.add() parameter a='a' violates type hint <class 'int'>, as str 'a' not instance of int.
profile
Hello, I'm Terry! 👋 Enjoy every moment of your life! 🌱 My current interests are Signal processing, Machine learning, Python, Database, LLM & RAG, MCP & ADK, Multi-Agents, Physical AI, ROS2...

0개의 댓글