pythonbeginner
pythonbeginner

Reputation: 9

why does python decorator make a function to return "None"?

Guys can someone help me to understand why doesn't my python decorator work properly?

created a decorator that would print the below mentioned text after returning the count of car_fuel() function.

def decor(func):
    def wrapper(a):
        func(a)
        print('Bring 10 coupons and get a gallon of fuel for free')
    return wrapper



@decor
def car_fuel(a):
    b={'petrol':3.6,'diesel':3} #types of fuel and prices
    count = 0
    for i in a.keys():
        if i in b.keys():
            count+= a[i]*b[i]
    return count


abc={'petrol':10} # the fuel that i wanna buy and gallons
print(car_fuel(abc))

I want to have the following result:

36 Bring 10 coupons and get a gallon of fuel for free

but what I get is:

Bring 10 coupons and get a gallon of fuel for free None

Why don't I receive 36 before the "Bring 10 coupons...." sentence and why does it return None?

Upvotes: 0

Views: 417

Answers (2)

pythonbeginner
pythonbeginner

Reputation: 9

I edited the decorator. now it works properly thanks @rdas.

`def decor(func):
        def wraper(a):
            r=func(a)

            return str(r)+'\n'+'bring 10 coupons and get 10l free fuel'
        return wraper`

Upvotes: 0

rdas
rdas

Reputation: 21285

Because your wrapped function doesn't return anything - in python that means an implicit return None.

Fix:

def decor(func):
    def wraper(a):
        ret = func(a) # save return value
        print('Bring 10 coupons and get a gallon of fuel for free')
        return ret    # return it
    return wraper

Output:

Bring 10 coupons and get a gallon of fuel for free
36.0

Upvotes: 4

Related Questions