Sobes.tech
Middle

What is a decorator in Python? How does it work? How to create a decorator with arguments?

sobes.tech AI

Answer from AI

A decorator in Python is a function that takes another function and returns a new function with extended or modified behavior, without changing the source code of the decorated function.

How it works:

  • The decorator takes a function as an argument.
  • Inside, a nested function (wrapper) is created, which calls the original function and adds additional functionality.
  • The decorator returns this wrapper.

Example of a simple decorator:

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():
    print("Hello")

say_hello()

A decorator with arguments is a function that returns a decorator. This is a three-level structure:

def decorator_with_args(arg1, arg2):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"Decorator arguments: {arg1}, {arg2}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@decorator_with_args('foo', 'bar')
def greet(name):
    print(f"Hello, {name}!")

greet('Alice')

Thus, decorators allow convenient extension of function behavior.

What is a decorator in Python? How does it work? How… - sobes.tech