Jon Warneke Jon Warneke - 6 months ago 9
Python Question

python decorator above something other than def

The usual construct for a decorator in python is

@decorator
def function(x):
<code here>


which is equivalent to

def function(x):
<code here>
function = decorator(function)


(At least, this is my understanding.) Now suppose we are given a function
mystery_func
which we didn't define ourselves but we'd still like to decorate with
decorator
. Can we do

@decorator
mystery_func


or do we have to do

mystery_func = decorator(mystery_func)


to get the same effect as

@decorator
def mystery_func(args):
<code here>

Answer

The answer is no, the @ syntax cannot be used with arbitrary lines, you need to use mystery_func = decorator(mystery_func). Using the @ syntax like this is a SyntaxError.