wraps를 쓰지않아도 데코레이터는 구현할 수 있다. 단, functools.wraps
를 쓰면 실사용 함수의
__name__
과 __doc__
을 사용할 수 있도록 해준다.
import timer
from functools import wraps
def timer(func):
def wrapper(*args, **kwrags):
"""this is wrapper docstring"""
start = time.time()
result = func(*args, **kwargs)
print(f"실행완료: {time.time() - start:.2f}초")
return result
return wrapper
def timer_with_wraps(func):
@wraps(func)
def wrapper(*args, **kwrags):
"""this is wrapper docstring"""
start = time.time()
result = func(*args, **kwargs)
print(f"실행완료: {time.time() - start:.2f}초")
return result
return wrapper
@timer
def test1():
"""this is test1 docstring"""
sum = 0
for i in range(1000):
sum += i
return sum
@timer_with_wraps
def test2():
"""this is test2 docstring"""
sum = 0
for i in range(1000):
sum += i
return sum
위와 같은 코드가 있다. 이때 각 test1과 test2의 docstring과 함수 이름을 출력해보자.
>> test1.__doc__
this is wrapper docstring
>> test1.__name__
wrapper
>> test2.__doc__
this is test2 docstring
>> test2.__name__
test2
test1은 래핑함수의 __doc__
, __name__
이 출력되지만, test2는 test2의 속성이 출력된다. 이렇게 functools.wraps
를 쓰지않아도 데코레이터는 구현할 수 있지만, 문서속성을 제대로 가져올 수 있다.