Learning decorators and I wanted to pass a function with arguments to a decorator function like shown below but I always get a syntax error. Please help!
JavaScript
x
13
13
1
def decorator(func(*args)):
2
def wrapper():
3
print('up')
4
func(*args)
5
print('down')
6
return wrapper
7
8
@decorator
9
def func(n):
10
print(n)
11
12
func('middle')
13
Output:
JavaScript
1
5
1
File "<ipython-input-21-c2d727543f8e>", line 1
2
def decorator(func(*args)):
3
^
4
SyntaxError: invalid syntax
5
Advertisement
Answer
Your syntax is incorrect. To define a correct decorator and wrapper function, see what follows:
JavaScript
1
13
13
1
def decorator(func): # assign the function you want to pass
2
def wrapper(*args): # assign the parameters you want to use for the function
3
print('up')
4
func(*args)
5
print('down')
6
return wrapper
7
8
@decorator
9
def func(n): # The function you want to decorate
10
print(n)
11
12
func('middle')
13
Output:
JavaScript
1
4
1
up
2
middle
3
down
4