How to Add a Decorator to a Class on the Fly

Posted by

<!DOCTYPE html>

Dynamically Adding a Decorator to a Class

Dynamically Adding a Decorator to a Class

Decorators are a powerful feature in Python that allows you to add extra functionality to a class or function. They are commonly used to add logging, caching, or validation to your code without modifying the original class or function.

One interesting use case for decorators is the ability to dynamically add a decorator to a class. This can be useful when you want to apply a decorator only under certain conditions or at runtime.

Below is an example of how you can dynamically add a decorator to a class in Python:


        class MyDecorator:
            def __init__(self, func):
                self.func = func

            def __call__(self, *args, **kwargs):
                print('Decorator added dynamically...')
                return self.func(*args, **kwargs)

        def add_decorator(cls):
            cls.my_method = MyDecorator(cls.my_method)
            return cls

        @add_decorator
        class MyClass:
            def my_method(self):
                print('Original method...')
    

In this example, we define a custom decorator class MyDecorator that prints a message before calling the original method. We also define a function add_decorator that adds an instance of MyDecorator to the my_method of a class.

By using the @add_decorator syntax, we can dynamically add the MyDecorator to the MyClass class. When we call the my_method of MyClass, it will print the message defined in MyDecorator before executing the original method.

Overall, dynamically adding a decorator to a class can be a powerful technique to add extra functionality to your code in a flexible and dynamic way.