💻 Programming

Decorator

Decorator

A wrapper that modifies the behavior of a function or class. Python's @decorator syntax. Used in metaprogramming.

📖 Detailed Explanation

A decorator is a design pattern and syntax that modifies or extends the behavior of a function or class. It is widely used in Python through the @decorator syntax, and in JavaScript/TypeScript through the experimental decorator feature.

A Python decorator is essentially a higher-order function that takes a function as an argument and returns a new function. If you decorate a function with @log_time, you can add logic that measures time before and after that function is called. This extends functionality without modifying the original function code.

Decorators are useful for handling cross-cutting concerns. If you extract functionality that applies in common to many functions, such as logging, authentication, caching, retry logic, and input validation, into a decorator, you can reduce code duplication and separate concerns.

A class decorator wraps or modifies an entire class. Python's @dataclass automatically generates __init__, __repr__, and so on for a class. Multiple decorators can be stacked and are applied from bottom to top.

💻 Code Example

Python
import functools
import time

# 기본 데코레이터: 실행 시간 측정
def timer(func):
    @functools.wraps(func)  # 원본 함수의 메타데이터 보존
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 실행 시간: {end - start:.4f}초")
        return result
    return wrapper

# 인자를 받는 데코레이터
def retry(max_attempts=3):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"시도 {attempt + 1} 실패: {e}")
            raise Exception(f"{max_attempts}번 시도 모두 실패")
        return wrapper
    return decorator

# 데코레이터 적용
@timer
@retry(max_attempts=3)
def fetch_data(url):
    print(f"데이터 가져오는 중: {url}")
    return {"data": "결과"}

# 클래스 메서드 데코레이터
class API:
    @staticmethod
    def require_auth(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            if not self.is_authenticated:
                raise PermissionError("인증 필요")
            return func(self, *args, **kwargs)
        return wrapper

# 사용
result = fetch_data("https://api.example.com")

🗣️ Examples of Practical Conversations

Backend developer
"The authentication check code is duplicated in every API endpoint. What if we pull it out into a decorator?"
Senior developer
"Sounds good. If we create an @require_auth decorator, we only need to add one line to each handler, so it'll be much cleaner."
Backend developer
"It would be even better to create separate decorators for each permission level and distinguish them as @require_admin and @require_user."
Interviewer
"Please explain how decorators work in Python."
Candidate
"A decorator is a higher-order function that takes a function as an argument and returns a new function. @decorator is equivalent to func = decorator(func). It wraps the original function and adds pre-processing or post-processing logic."
Interviewer
"Why do we use functools.wraps?"
Candidate
"When you wrap a function with a decorator, the original function's metadata such as __name__ and __doc__ is replaced by that of the wrapper function. Using wraps preserves the original function's metadata, which is beneficial for debugging and documentation."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"This decorator is missing functools.wraps. If we don't add it, the function name shows up as wrapper, which makes debugging harder."
Author
"Ah, right. We need to trace function names in production logs, so this is an important part. I'll add it right away."
Reviewer
"Also, please check the decorator order. If you put @timer after @cache, time is measured even on cache hits, which leaves meaningless logs."

⚠️ Cautions

🔗 Related Terms

📚 Learn More