Sobes.tech
Junior — Middle

Explain the concept of decorators in Python and how they are used to modify the behavior of functions.

sobes.tech AI

Answer from AI

Decorators in Python are functions that take another function and return a new function with modified or extended behavior, without changing the original code of the decorated function.

They are often used for:

  • Logging calls
  • Access rights checks
  • Caching results
  • Measuring execution time

Here's an example of a simple decorator that prints a message before and after calling a function:

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs)
        print("After calling the function")
        return result
    return wrapper

@decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

The output will be:

Before calling the function
Hello, World!
After calling the function

Thus, decorators allow dynamically changing the behavior of functions without modifying their source code.