Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorated function returns None

I have a decorator that checks a function's argument for int type.

def check_type_int(old_function):
    def new_function(arg):
        if not isinstance(arg, int):
            print 'Bad Type'    # raise TypeError('Bad Type')
        else:
            old_function(arg)
    return new_function

When I run a decorated function, it returns None instead of an int value.

@check_type_int
def times2(num):
    return num*2

times2('Not A Number')  # prints "Bad Type"
print times2(2)         # prints "None"

The last line should print 4. Can someone please spot my mistake? Thanks.

like image 666
Lokesh Meher Avatar asked Feb 07 '23 18:02

Lokesh Meher


1 Answers

You don't return any value from new_function inside the decorator, therefore it returns None by default. Just change this line:

old_function(arg)

to

return old_function(arg)
like image 59
Eugene Yarmash Avatar answered Feb 11 '23 16:02

Eugene Yarmash