Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass decorator default value to inner function in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading