Sobes.tech
Middle

What is a decorator in Python and in what cases can it be used?

sobes.tech AI

Answer from AI

A decorator is a special type of function that takes another function as an argument, extends its functionality, and returns a new (decorated) function without modifying the original code of the decorated function. It is used to wrap functions or methods and control their behavior.

It is applied in cases such as:

  • Logging: Recording information about function calls (arguments, results, execution time).
  • Measuring execution time: Determining the performance of a function.
  • Access control: Restricting function execution for certain users or groups.
  • Caching: Saving the results of function execution for reuse with the same arguments.
  • Error handling: Catching exceptions and performing additional actions.
  • Retry on error: Automatically retrying upon certain exceptions.
  • Function registration: Adding functions to a registry or collection.

Example of a simple decorator:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Doing something before calling the function")
        result = func(*args, **kwargs)
        print("Doing something after calling the function")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    return f"Hello, {name}!"

# say_hello("world") # Will output:
# Doing something before calling the function
# Doing something after calling the function
# "Hello, {name}!"