Incendere Taief
Incendere Taief

Reputation: 15

Program works but I still get a NoneType error Python Decorators

So I'm very new and decided to try out decorators and basically it adds "Start" before showing the name, and "End" afterwards. Very simple, and it works, but I get a NoneType error?

def start_end_decorator(func):

    def wrapper():
        print("Start")
        func()
        print("End")
    return wrapper()

@start_end_decorator
def print_name():
    print ('Nero')

print_name()

here's the output:

line 13, in <module>
    print_name()
TypeError: 'NoneType' object is not callable
Start
Nero

I'm so confused? Should I just ignore it with maybe a try/except? End

Upvotes: 0

Views: 47

Answers (3)

sachin Dhavane
sachin Dhavane

Reputation: 1

def start_end_decorator(func):

def wrapper(*args,**kwargs):
    print('start')
    
    result=func(*args,**kwargs)
    
    print('End')
    
    return result
return wrapper

@start_end_decorator
def add(x): print (x) return x+5

result=add (100) print(result)

O/P: start 100 End 105

Upvotes: 0

Michael
Michael

Reputation: 2414

The function wrapper doesn't have a return statement in it, so it returns None. Therefore this line in start_end_decorator():

return wrapper()

returns None. Your intention was surely to return the function, not the function's return value. Try changing that statement to this:

return wrapper

Upvotes: 3

Daniel Walker
Daniel Walker

Reputation: 6760

A decorator has to return a callable object. start_end_decorator, however, is returning the return value of wrapper. Since wrapper has no return statement, None is implicitly returned. None is not a callable object hence the error.

What you want is to return wrapper from your decorator instead of wrapper().

Upvotes: 0

Related Questions