Suppose that for administrative reasons I do not have write access to module xxx.
I want to do something like:
from xxx import yyy
@myDeco
yyy
which of course fails.
I think I can do
yyy = myDeco(yyy)
but is there a way to use the @myDeco” notation ? Or is this only permitted immediately before a def?
In the Python reference documentation, Compound Statements section, it says:
This is part of the syntax rules. As you can see, decorators are only applied before a function or class definition, which is what
def <funcname>starts. It goes on, noting:That said, keep in mind that decorators are really just syntactic sugar, and before they were made available the form:
Was used instead. So if all you have is the function object in some variable, you can’t use the decorator syntactic sugar and must revert to the second method.