Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you put a decorator after you've written it?

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?

like image 372
Malik A. Rumi Avatar asked Jan 02 '23 10:01

Malik A. Rumi


1 Answers

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.

like image 86
wim Avatar answered Jan 16 '23 22:01

wim