1

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!

def decorator(func(*args)):
    def wrapper():
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')

Output:

File "<ipython-input-21-c2d727543f8e>", line 1
    def decorator(func(*args)):
                      ^
SyntaxError: invalid syntax
1
  • You aren't passing anything, that's your function signature. Commented Jun 1, 2020 at 16:43

2 Answers 2

3

Your syntax is incorrect. To define a correct decorator and wrapper function, see what follows:

def decorator(func):       # assign the function you want to pass
    def wrapper(*args):    # assign the parameters you want to use for the function
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):               # The function you want to decorate
    print(n)

func('middle')

Output:

up
middle
down
Sign up to request clarification or add additional context in comments.

Comments

0

Just a few changes: arguments for a function you need to provide as *args inside wrapper. And and another thing - remove *args from decorator(func(*args)).

def decorator(func):
    def wrapper(*args):
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.