Home > Software engineering >  How to pass decorator default value to inner function in Python
How to pass decorator default value to inner function in Python

Time:10-18

I'm learning about function decorators and am trying to apply some of the concepts I've learned so far. For the below function i've created a decorator function but it doesnt behave as I would expect.

Can someone help me understand why I can't access the default value (or any provided arg) of the outer function so that I can use it in the inner function? I keep getting a TypeError: type function doesn't define __round__ method.

def mathTool(defaultVal=5):
        def innerFunc(*args):
            return round(*args, defaultVal)
        return innerFunc

print(funcB()) //triggers TypeError
print(funcB(2)) //triggers TypeError

def funcA(A):
    return A/2

@mathTool()
def funcB(B):
    return B/2

def funcAB(A, B):
     return A*B/2

func_dec = mathTool(defaultVal=7)(funcAB)

print(func_dec(5, 9)) //triggers TypeError

CodePudding user response:

Decorators take exactly one argument: the function. And their syntax is this:

@deco
def func():
    ...

When you see a decorator which takes arguments, as in @deco(arg), that is actually a function which returns a decorator.

Therefore:

def mathTool(defaultVal=5):
    def decorator(func):
        def innerFunc(*args):
            args = args   (defaultVal,)
            return func(*args)
        return innerFunc
    return decorator

@mathTool(7)
def whatever(a, b):
    ...

Now, calling whatever(1) will pass 1 and 7 to the function.

  • Related