Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using a decorator and explicitly calling it?

Let's assume we have a decorator:

def decor(function):
    def result():
        printf('decorated')
        return function()
    return result

What is the difference between following code:

@decor
def my_foo():
    print('my_foo')

and:

def my_foo():
    print('my_foo')
my_foo = decor(my_foo)
like image 462
gruszczy Avatar asked Dec 16 '22 05:12

gruszczy


2 Answers

Your last code snippet is almost the definition of a decorator. The only difference is that in the first case, the name decor is evaluated before the function definition, while in the second case it is evaluated after the function definition. This only makes a difference if executing the function definition changes what the name refers to.

Nonsensical example:

def decor(function):
    def result():
        printf('decorated')
        return function()
    return result

def plonk():
    global decor
    decor = lambda x: x
    return None

Now

@decor
def my_foo(foo=plonk()):
    print('my_foo')

is different from

def my_foo(foo=plonk()):
    print('my_foo')
my_foo = decor(my_foo)
like image 146
Sven Marnach Avatar answered Dec 22 '22 00:12

Sven Marnach


There isn't a difference. The @decorator syntax simply makes it easier to understand that a decorator is being applied. (This is an example of syntactic sugar.)

like image 29
Noah Avatar answered Dec 21 '22 23:12

Noah