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

Suppose we have a decorator:

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

What is the difference between the following code:

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

and

 def my_foo(): print('my_foo') my_foo = decor(my_foo) 
+4
source share
3 answers

Your last piece of code is almost the definition of a decorator. The only difference is that in the first case, the name decor is evaluated before the function is defined, and in the second, after the function is defined. This only matters if the execution of the function definition changes the name to which it refers.

Undemanding 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') 

differs from

 def my_foo(foo=plonk()): print('my_foo') my_foo = decor(my_foo) 
+7
source

There is no difference. The @decorator syntax just makes it easier to understand that a decorator is being used. (This is an example of syntactic sugar .)

+4
source

If there is a difference, it is that versions of python prior to Python 2.4 do not support @decorator syntax, while explicit decorator calls have been supported since the Stone Age. In addition, the @decorator syntax should have been used to define the function and should have used the same function name, while an explicit call to the decorator can be applied later and can rename the decorated function.

Use the @decorator syntax if you haven’t had a good reason really, really, really ; which almost never works.

+1
source

Source: https://habr.com/ru/post/1389831/


All Articles