728x90
@wraps는 Python에서 표준 라이브러리의 functools 모듈에 포함된 데코레이터입니다. 주로 데코레이터를 만들 때 사용되며, 원본 함수의 메타데이터(예: 함수명, 문서화 문자열 등)를 데코레이터로 감싸진 함수에 복사하는 역할을 합니다.
@wraps의 사용 이유
데코레이터를 사용할 때, 원래 함수의 이름이나 문서 문자열(__name__, __doc__ 등)이 덮어씌워지는 문제가 발생할 수 있습니다. 이를 방지하고, 원래 함수의 메타데이터를 유지하기 위해 @wraps를 사용합니다.
예시: @wraps 사용
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before the function runs")
result = func(*args, **kwargs)
print("After the function runs")
return result
return wrapper
@my_decorator
def say_hello():
"""This function says hello"""
print("Hello!")
say_hello()
# 원본 함수의 메타데이터 유지 확인
print(say_hello.__name__) # say_hello
print(say_hello.__doc__) # This function says hello
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before the function runs")
result = func(*args, **kwargs)
print("After the function runs")
return result
return wrapper
@my_decorator
def say_hello():
"""This function says hello"""
print("Hello!")
say_hello()
# 원본 함수의 메타데이터 유지 확인
print(say_hello.__name__) # say_hello
print(say_hello.__doc__) # This function says hello
@wraps 없이 데코레이터 사용 시
만약 @wraps를 사용하지 않고 위와 같은 데코레이터를 만들었다면, 다음과 같은 문제가 발생합니다:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function runs")
result = func(*args, **kwargs)
print("After the function runs")
return result
return wrapper
@my_decorator
def say_hello():
"""This function says hello"""
print("Hello!")
say_hello()
# 원본 함수의 메타데이터 유지 확인
print(say_hello.__name__) # wrapper
print(say_hello.__doc__) # None
def wrapper(*args, **kwargs):
print("Before the function runs")
result = func(*args, **kwargs)
print("After the function runs")
return result
return wrapper
@my_decorator
def say_hello():
"""This function says hello"""
print("Hello!")
say_hello()
# 원본 함수의 메타데이터 유지 확인
print(say_hello.__name__) # wrapper
print(say_hello.__doc__) # None
@wraps 없이 데코레이터를 사용하면, say_hello 함수의 이름이 wrapper로 바뀌고, 문서화 문자열(__doc__)이 사라지게 됩니다. 따라서 @wraps는 데코레이터를 사용할 때 원본 함수의 메타데이터를 유지하는 데 매우 유용합니다.
728x90
'개발 > Python' 카테고리의 다른 글
[Python] pip install 종속성 오류 해결 명렁어 (0) | 2025.01.05 |
---|---|
[Python] @classmethod vs getter, setter 사용 (0) | 2024.07.04 |
Python - 내가 만든 모듈, 다른 사람들이 사용하도록 패키징하기 (0) | 2024.03.15 |
Python 정적 메소드(@staticmethod) (0) | 2024.03.14 |
파이썬 EXE 파일 만들기 (0) | 2023.12.31 |