0

I know we can create basic decorator this way :

def printArgs(function):
    def wrapper(*args, **kwargs):
        print(args, kwargs)
        return function(*args, **kwargs)
    return wrapper

class A:
    @printArgs
    def add(self, number1, number2):
        return number1 + number2

I would like to create a decorator that take additional arguments like this :

def addXToResult(function, x):
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs) + x
    return wrapper

But when I try to use this second decorator, I have the missing 1 required positional argument: 'x' appearing:

class A:
    @addXToResult(2)
    def add(self, number1, number2):
        return number1 + number2

If I try to change it to @addXToResult(A.add, 2) I get NameError: name 'A' is not defined.

Why is it that in the first case, the decorated function is passed automatically as parameter (like the self is automatically filled in class method) ?

How am I supposed to create a decorator with additional parameters ?

Xiidref
  • 1,456
  • 8
  • 20
  • 1
    You are using the word `annotation`. I think you mean `decorator`. – quamrana Oct 17 '22 at 09:36
  • Yes, sorry, I got confused over the term to use. It's decorator (and suddenly my Google research return me more pertinent results). – Xiidref Oct 17 '22 at 09:43

0 Answers0