I am trying my hand at writing my first decorator. I have seen lots of video tutorials and blog posts about it, but I have not seen anything about where to put the decorator so that the function being decorated can find it. That seems pretty basic, and maybe it is 'obvious' to those who have done it before, but since that's not me, I am asking. Note I am not asking where to put @decorator. I know that goes on the line above the function being decorated. But the decorator itself has to be written and put somewhere where the @ syntax can find and apply it. All the examples I've seen have them both in the same file or script, but I have never seen a decorator like that in actual practice, nor have I seen an import statement that brings it into the app. So where should it be, and how does the decorated app / python find it?
A decorator is just a callable, usually a function. It means you can define it anywhere you would like any other function and import it the same way.
from mydecorators import mydecorator
@mydecorator
def f():
...
Since decoration of a module-level class or function happens at import time, the name must be resolved before it used. This prohibits defining or importing the decorator after using it, which will be a NameError
exception as usual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With