DEV Community

nomi3
nomi3

Posted on

How to Override Decorator Arguments in Python

To override the decorator arguments used in a parent class method within a child class, you need to override the method in the child class. Simply declaring new class variables with the same names will not affect the decorator arguments unless you explicitly redefine the method.

Sample Code

Save the following as test.py

def my_decorator_with_args(param1, param2):
    """Decorator that takes arguments"""

    def actual_decorator(func):
        def wrapper(self, *args, **kwargs):
            print(f"[Decorator] param1={param1}, param2={param2}")
            return func(self, *args, **kwargs)

        return wrapper

    return actual_decorator


class BaseClass:
    @my_decorator_with_args(param1="BASE_PARAM1", param2="BASE_PARAM2")
    def greet(self):
        print("Hello from BaseClass!")


class DerivedClass(BaseClass):
    """
    Intending to override the decorator arguments by defining class variables,
    but since greet() itself is not redefined (overridden),
    the parent class's decorator is actually used as is.
    """

    param1 = "DERIVED_PARAM1"
    param2 = "DERIVED_PARAM2"
    # greet() is intentionally not redefined


class DerivedClassOverride(BaseClass):
    """
    This pattern redefines (overrides) the greet() method
    to change the decorator arguments.
    """

    @my_decorator_with_args(param1="OVERRIDE_PARAM1", param2="OVERRIDE_PARAM2")
    def greet(self):
        print("Hello from DerivedClassOverride!")


if __name__ == "__main__":
    print("=== BaseClass's greet ===")
    b = BaseClass()
    b.greet()

    print("\n=== DerivedClass's greet (without override) ===")
    d = DerivedClass()
    d.greet()

    print("\n=== DerivedClassOverride's greet (with override) ===")
    d_o = DerivedClassOverride()
    d_o.greet()
Enter fullscreen mode Exit fullscreen mode

then run:

python test.py
Enter fullscreen mode Exit fullscreen mode

Result

=== BaseClass's greet ===
[Decorator] param1=BASE_PARAM1, param2=BASE_PARAM2
Hello from BaseClass!

=== DerivedClass's greet (without override) ===
[Decorator] param1=BASE_PARAM1, param2=BASE_PARAM2
Hello from BaseClass!

=== DerivedClassOverride's greet (with override) ===
[Decorator] param1=OVERRIDE_PARAM1, param2=OVERRIDE_PARAM2
Hello from DerivedClassOverride!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)