Understanding Decorators in Python with Examples

Q: What is a decorator in Python? Can you provide an example of a decorator function?

  • Python
  • Mid level question
Share on:
    Linked IN Icon Twitter Icon FB Icon
Explore all the latest Python interview questions and answers
Explore
Most Recent & up-to date
100% Actual interview focused
Create Interview
Create Python interview for FREE!

Python decorators are a powerful tool that allows developers to modify or enhance functions or methods without changing their actual code. They're widely used in Python programming, especially in frameworks like Flask and Django, for adding functionality such as access control, logging, caching, and more. The decorator pattern is an elegant solution that can help keep code modular and maintainable.

In essence, decorators are simply functions that take another function as an argument, adding functionality or behavior to it. These higher-order functions are crucial in Python, as they provide a clear way to implement reusable code patterns. Understanding how decorators work can significantly enhance your coding skills and make you a better Python programmer.

Interview candidates should be prepared to discuss decorators, especially in roles that involve Python development. Familiarity with the syntax and the underlying principles will show potential employers that you grasp advanced Python concepts. In addition, knowing how decorators can be used in real-world scenarios, such as in implementing middleware for web frameworks, can be an impressive addition to your skill set.

Notably, decorators can be classified into several types, including function decorators, class decorators, and method decorators, each serving different purposes but sharing common principles. They often interact seamlessly with Python’s capabilities like closures and first-class functions, which means you should also understand these foundational concepts. Overall, mastering decorators can pave the way for writing cleaner, more efficient Python code. Candidates preparing for technical interviews should ensure they not only understand what decorators are but also practice writing and applying them in diverse contexts to boost their confidence and coding agility..

In Python, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Decorators allow for the dynamic modification of a function or a class at runtime.

Here's an example of a decorator function that adds timing functionality to another function:

import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start} seconds to execute.") return result return wrapper @timer def my_function(): # some code here pass my_function()

In this example, timer is a decorator function that takes the my_function function as its argument. It defines a new function, wrapper, which takes any number of arguments (*args) and keyword arguments (**kwargs). The wrapper function calls the original function (func(*args, **kwargs)) and calculates the time it takes to execute it. Finally, it prints the elapsed time and returns the result of the original function. The decorator function is applied to the my_function function using the @ symbol to create a new decorated function.