Sobes.tech
Middle

How can you pass a variable to a decorator in Python?

sobes.tech AI

Answer from AI

Passing variables to a decorator is possible through a decorator factory function.

# Decorator factory takes arguments
def decorator_factory(arg1, arg2):
    # Returns the decorator itself (closure)
    def my_decorator(func):
        # Wrapper function
        def wrapper(*args, **kwargs):
            print(f"Argument 1: {arg1}, Argument 2: {arg2}")
            return func(*args, **kwargs)
        return wrapper
    return my_decorator

# Using the decorator with arguments
@decorator_factory("value 1", 123)
def my_function():
    print("Decorated function is executing")

# Calling the function
my_function()
How can you pass a variable to a decorator in Python… - sobes.tech