HomeInterview QuestionsHave you used decorators in Python? What is their …

Have you used decorators in Python? What is their use?

🟡 Medium Conceptual Junior level
1Times asked
May 2026Last seen
May 2026First seen

💡 Model Answer

Decorators in Python are a syntactic convenience that allows you to modify or extend the behavior of functions or classes without changing their code. A decorator is a callable that takes a function (or class) as an argument and returns a new function (or class). The @decorator syntax is shorthand for assigning the result of the decorator to the original name. Common use cases include logging, authentication, caching, and input validation. For example, a simple timing decorator can measure execution time:

python
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.4f}s")
        return result
    return wrapper

@timer
def compute(x):
    return sum(i for i in range(x))

When compute is called, the wrapper runs first, timing the call and then invoking the original function. Decorators can also be parameterized by returning a decorator factory. They promote code reuse, separation of concerns, and cleaner APIs. Understanding how to write and apply decorators is essential for advanced Python development, especially in frameworks like Flask or Django where decorators are used for routing, authentication, and middleware.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500