Decorator
Decorator
A wrapper that modifies function/class behavior. Python @decorator syntax. Metaprogramming.
Decorator
A wrapper that modifies function/class behavior. Python @decorator syntax. Metaprogramming.
A decorator is a design pattern that adds new functionality to an existing function or class without directly modifying its code. It works by wrapping the original code, and allows cross-cutting concerns such as logging, authentication, and caching to be cleanly separated.
In Python, a decorator is syntactic sugar that uses the @ symbol, and is a higher-order function that takes a function as an argument and returns a new function. @decorator is actually equivalent to func = decorator(func), and it was introduced in PEP 318 in 2003 and has since become a core feature of Python.
In TypeScript, a decorator is a special declaration that adds metadata to, or modifies the behavior of, a class, method, property, or parameter. It is currently at the TC39 Stage 3 proposal stage, and it is used as an essential part of dependency injection and routing in major frameworks such as Angular and NestJS.
In practice, decorators are a core tool of AOP (aspect-oriented programming), significantly improving code reusability and maintainability by separating business logic from auxiliary functionality. Flask's @app.route, Django's @login_required, and NestJS's @Controller are representative examples.
# 1. 기본 데코레이터 - 실행 시간 측정
import time
import functools
def timer(func):
@functools.wraps(func) # 원본 함수 메타데이터 보존
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} 실행 시간: {end - start:.4f}초")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "완료"
slow_function() # 출력: slow_function 실행 시간: 1.0012초
# 2. 인자를 받는 데코레이터 - 재시도 로직
def retry(max_attempts=3, delay=1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts:
raise
print(f"시도 {attempt} 실패, {delay}초 후 재시도...")
time.sleep(delay)
return wrapper
return decorator
@retry(max_attempts=3, delay=2)
def fetch_data(url):
# API 호출 로직
pass
# 3. 클래스 데코레이터 - 싱글톤 패턴
def singleton(cls):
instances = {}
@functools.wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Database:
def __init__(self):
print("DB 연결 생성")
db1 = Database() # 출력: DB 연결 생성
db2 = Database() # 출력 없음 (같은 인스턴스 반환)
print(db1 is db2) # True
"Authentication logic is being duplicated in every API endpoint. If we create a @login_required decorator and apply it in common, we can reduce code duplication, and when the security policy changes, we only need to modify one place."
"The decorator pattern is a good way to implement the OCP (Open-Closed Principle). You can extend an existing function without modifying it, and in Python you should use functools.wraps to preserve the original function's metadata such as __name__ and __doc__, which makes debugging easier."
"This decorator is missing functools.wraps. As a result, the __name__ of the decorated function comes out as 'wrapper', which can cause confusion when logging or debugging. Please add @functools.wraps(func)."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If you omit @functools.wraps(func), the original function's __name__, __doc__, and __annotations__ are lost. During debugging, all function names appear as 'wrapper', making tracing difficult.
When multiple decorators are stacked, they are applied from bottom to top. @a @b @c def func() is equivalent to a(b(c(func))). Behavior may differ depending on the order, so check that it is the intended order.
To accept arguments like @decorator(arg), you need to wrap the function one more level. A triple-nested structure is required: decorator(arg) -> actual_decorator(func) -> wrapper(*args).