본문 바로가기
Q&A2022년 4월 13일1분 읽기

Python 데코레이터 이해하기

김
김민수
조회 709댓글 1

Python 데코레이터(@decorator)가 뭔지 쉽게 설명해주세요.

댓글 1

김김영삼4년 전

데코레이터는 함수를 감싸서 기능을 추가하는 패턴입니다.

# 기본 데코레이터
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__}: {time.time()-start:.2f}s")
return result
return wrapper

@timer
def slow_function():
import time
time.sleep(1)
return "done"

slow_function() # slow_function: 1.00s

# 인자 있는 데코레이터
def retry(times=3):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(times):
try: return func(*args, **kwargs)
except Exception as e:
if i == times-1: raise
return wrapper
return decorator

@retry(times=5)
def api_call():
...

Flask의 @app.route, pytest의 @pytest.fixture가 대표적인 데코레이터 활용입니다.

Ctrl+Enter로 등록