DeployU
Interviews / Backend Engineering / What are decorators and how do you use them in Python?

What are decorators and how do you use them in Python?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new service that has several functions that need to be timed to measure their performance.

You could add the timing code to each function, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.

The Challenge

Explain what decorators are in Python and how you would use them to solve this problem. What are the key benefits of using decorators?

Wrong Approach

A junior engineer might not be aware of decorators. They might try to solve the problem by adding the timing code to each function, which would be repetitive and difficult to maintain.

Right Approach

A senior engineer would know that decorators are the perfect tool for this job. They would be able to explain what decorators are and how to use them to add functionality to existing functions without modifying their code.

Step 1: Understand What Decorators Are

A decorator is a function that takes another function as an argument and returns a new function that adds some functionality to the original function.

Step 2: Write a Simple Decorator

Here’s how we can write a simple decorator to time a function:

import time

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.2f} seconds to run.")
        return result
    return wrapper

Step 3: Apply the Decorator

We can apply the decorator to a function using the @ symbol:

@timing_decorator
def my_function():
  # ... (some long-running code) ...

Now, whenever we call my_function(), the timing_decorator will be automatically applied to it, and the execution time will be printed to the console.

The Benefits of Using Decorators

BenefitDescription
ReusabilityYou can reuse the same decorator on multiple functions.
MaintainabilityYou can change the functionality of all the decorated functions by just changing the decorator.
ReadabilityDecorators make it clear what functionality is being added to a function.

Practice Question

You want to create a decorator that can accept arguments. What should you do?