<vetted />
Python
Mid-Level
Question 2 of 7

How do decorators work in Python and when would you use them?

Quick Answer

Decorators are functions that modify other functions, enabling reusable patterns like logging, timing, authentication, and caching.

Detailed Answer7 paragraphs

Decorators in Python are a powerful pattern that allows you to modify or extend the behavior of functions or classes without changing their source code.

A decorator is simply a function that takes a function as input and returns a new function. The @decorator syntax is syntactic sugar: @my_decorator above a function definition is equivalent to func = my_decorator(func).

Basic structure: def my_decorator(func): def wrapper(*args, **kwargs): # Before function call result = func(*args, **kwargs) # After function call return result return wrapper. The wrapper function typically calls the original function while adding behavior.

Common use cases include: Logging (automatically log function calls and arguments), Timing (measure function execution time), Authentication/Authorization (check permissions before allowing execution), Caching/Memoization (cache results with @functools.lru_cache), Retry Logic (automatically retry failed operations), and Validation (validate inputs before function execution).

Decorators with arguments require an extra level of nesting: the outer function takes the arguments, returns the actual decorator, which returns the wrapper.

Best practices: Use @functools.wraps(func) in your wrapper to preserve the original function's metadata (name, docstring). Keep decorators focused on a single concern. Stack decorators (the bottom one is applied first). Consider using classes as decorators for stateful behavior.

Understanding decorators is essential for Python development, as they're used extensively in frameworks like Flask (@app.route), Django (@login_required), and testing libraries (@pytest.fixture).

Key Takeaway

Decorators are functions that modify other functions, enabling reusable patterns like logging, timing, authentication, and caching.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.