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)
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)
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.)
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