[Python] functools.wraps

오도원공육사·2022년 10월 4일
0

파이썬

목록 보기
8/11

기능

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를 쓰지않아도 데코레이터는 구현할 수 있지만, 문서속성을 제대로 가져올 수 있다.

profile
잘 먹고 잘살기

0개의 댓글