How to make decorators take effect when the program starts – Python

When decorators are applied to methods in other modules, if I want these decoration take effect, I need to load these modules.

Can I let them load when the program start?

I try to import all modules in can achieve this goal, is there any other way to do this?

>Solution :

It’s a little bit unclear what you want (a minimal, reproducible example would be a great help), but I’ll take a shot at explaining what decorators are and when their code is run. I’m basically going to be summarizing parts of the excellent Real Python article on decorators, which you should absolutely read for a complete understanding.

Decorators are just functions. Real Python gives this example:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        print("Something is happening after the function is called.")
    return wrapper

def say_whee():

say_whee = my_decorator(say_whee)

If you run it, it produces the following output:

>>> say_whee()
Something is happening before the function is called.
Something is happening after the function is called.

Now you’re probably thinking that I didn’t show you a decorator, just a wrapper function. Guess what? Same thing! A decorator is syntatic sugar for what we did above. In fact, we can use the same function in the same way as a decorator:

def say_whee():

So as to when decorators are run, the answer is, "whenever a decorated function is run." There’s nothing fancier or more mysterious going on than that. If you want your decorators to run, you need to run the decorated functions. If the decorated thing is a class, the decorator is run each time an instance of the class is instantiated, which, guess what, is achieved by running a function that the decorator(s) wrap.

Hopefully that clears things up a bit. Again, I would highly recommend reading the linked Real Python article for a more complete understanding.

Leave a Reply