Bot examples are incorrect. the outer function of a decorator (dec in this case) must take an argument which is the function it decorates.
So example 1 should look like this:
def dec(func):
def wrapper():
print(func)
return func
return wrapper
@dec
def hello():
print('hello')
hello()
Example two while doesn't crash immediately, would if you tried to call hello
(the decorated function).
For a decorator to take an argument you need another level of nesting.
So example 2 should look like this:
def dec_args(name):
def dec(func):
def wrapper():
print(func)
print(name)
return func
return wrapper
return dec
@dec_args('a')
def hello():
print('hello')
hello()
The inner decorator function (wrapper
) should take the argument that are passed to the decorated function (hello
). In these cases you don't have any
Also note that the wrapper
function doesn't really need to return func
. wrapper
is essentially a replacement of func
. That's what decorators do. They replace the function you decorate with the inner function of the decorator (by calling the outer function with the decorated function as an argument).