-3

I have two code snippets that look almost identical to one another. However, when I run them, the first code snippet works perfectly. When I run the second script, I get the error: TypeError: 'NoneType' object is not callable

Why???

I've tried renaming the functions. I've tried changing the text in the functions.

def cough_dec(func):
    def func_wrapper():
        print("*cough*")
        func()
        print("*cough*")

    return func_wrapper


@cough_dec
def question():
    print('can you give me a discount on that?')


@cough_dec
def answer():
    print("it's only 50p, you cheapskate")


question()
answer()

=============================================

def c_dec(func):

    def wrapper_func():
        print('something')
        func()
        print('anything')

    return wrapper_func()


@c_dec
def say_hello():
    print("Hello World!")


@c_dec
def bye():
    print("Goodbye World!")


say_hello()
bye()

If I remove the parentheses in the second snippet, everything works great, but why?

Alec
  • 8,529
  • 8
  • 37
  • 63
  • In the first snippet, your decorator cough_dec returns a function `return func_wrapper`, in the second snippet your decorator c_dec return the-ouput of the function `return func_wrapper()` which is None – phi May 22 '19 at 22:55

2 Answers2

1

Your wrapper_func() function does not return anything. Therefore , when you try to return the result of wrapper_func(), you get an error. In your first code snippet, you are returning the function object instead of the result of the function.

See this very similar question: Python NoneType object is not callable (beginner)

Conor Retra
  • 169
  • 5
0

There is a very big difference between referencing a function object and calling said function. Parentheses induce a function call. If no return statement is present in the function, the function returns None.

As one would expect, None is not callable, but a function object is!

Alec
  • 8,529
  • 8
  • 37
  • 63