0

I am trying to understand the concept of decorators in python when we have different arguments (In fact I am not sure how to pass arguments to the decorator). I have written the small and simple code below but I am not able to run it:

def advance(*arg, function):
    result = a * function(b, c)
    print(result)

@advance
def Sum1(b, c):
    return b + c

print(Sum1(1, 2, 3))

When running the code, I get TypeError: advance() missing 1 required keyword-only argument: 'function'.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
John Smith
  • 15
  • 5
  • 1
    `Sum1` becomes `arg[0]`, it's impossible to pass a keyword argument to the decorator (although you can to a decorator _factory_) using the `@` syntax. Also `a`, `b` and `c` are all undefined inside the decorator, which doesn't return a function to replace the wrapped function. – jonrsharpe Jul 26 '21 at 13:03
  • The way you have it written `advance` would only take one argument, and that argument would be a function. – Idr Jul 26 '21 at 13:05
  • Does this answer your question? [Python decorator? - can someone please explain this?](https://stackoverflow.com/questions/12046883/python-decorator-can-someone-please-explain-this) – jonrsharpe Jul 26 '21 at 13:05
  • Also https://stackoverflow.com/q/5929107/3001761, https://stackoverflow.com/q/739654/3001761 – jonrsharpe Jul 26 '21 at 13:06
  • The function is the *first* argument to `advance`, not the last. It helps to write out the use without decorator syntax. You define `Sum1`, then imagine `Sum1 = advance(Sum1)`. – chepner Jul 26 '21 at 13:25
  • [This](https://stackoverflow.com/a/1594484/13354437) is probably the best resource around for understanding and implementing decorators. It's a long read but it's worth it – Almog-at-Nailo Jul 26 '21 at 13:50

1 Answers1

1

Decorator has to return a new function, so you would like to have something like:

def advance(function):
    def wrapped(a, b, c):
        return a * function(b, c)
    return wrapped

@advance
def Sum1(b, c):
    return b + c

print(Sum1(10, 2, 3))
Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28