Home > Net >  Decorator Beginner __name__ is causing Type error
Decorator Beginner __name__ is causing Type error

Time:03-18

I have tried a few things to see if it had to do with when the functions were defined but to no avail I could not solve this. I am 90% sure the "name" method is causing the issue. But to me, this seems like it would be a good way to use a wrapper? Trying to explore wrapper because I am currently learning flask and they use wrappers off the get go with subdirectories. Thank you in advanced.

def smartCalc(func):
    def inner(a, b):
        if func.__name__ == "divide":
            print("I am going to divide"   str(a)   "and"   str(b))
            if b == 0:
                print("whoops! cannot divide")
                return
            return func(a, b)
        
        if func.__name__ == "Add":
            print("I am going to add", a, "and", b)
            return func(a, b)
        return inner



@smartCalc
def divide(a, b):
    print(a/b)

@smartCalc
def Add(a, b):
    print(a b)



Add(3,1)

TypeError: 'NoneType' object is not callable I was somewhat following this when I wanted to try something.

CodePudding user response:

You need to unindent the return inner, and execute func in all cases finally

def smartCalc(func):
    def inner(a, b):
        if func.__name__ == "divide":
            print("I am going to divide", a, "and", b)
            if b == 0:
                print("whoops! cannot divide")
                return
        if func.__name__ == "Add":
            print("I am going to add", a, "and", b)

        return func(a, b)

    return inner

CodePudding user response:

Your smartCalc defines an inner function, and then doesn't do anything else. It doesn't call the inner function, nor does it return something. So it always returns None.

Remember how

@smartCalc
def divide(a, b):
    print(a/b)

is just a fancy way of writing

def divide(a, b):
    print(a/b)
divide = smartCalc(divide)

? Well, now divide is None, so you can't call it anymore.

  • Related