Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'NoneType' object is not callable – python decorators

I am trying to understand Python decorators.
Tried this examples from FluentPython book. (Example 7.2, for reference(

# Using Decorators
registry = []

def register(func):
    print(f'running registry -> {func}')
    registry.append(func)


@register
def f1():
    print('running f1()')


@register
def f2():
    print('running f2()')


@register
def f3():
    print('running f3()')


def main():
    print('running registry')
    print(f'registry -> {registry}')
    f1()
    f2()
    f3()


if __name__ == '__main__':
    print('running main()')
    main()

But when i run this script it gives me error
> Traceback (most recent call last):
File "C:/Users/abcdef/Documents/FluentPython/NLP_C1_W1_lecture_nb_01.py", line 3, in

Examples.main()
File "C:\Users\abcdef\Documents\FluentPython\Examples.py", line 25, in main
f1()
TypeError: ‘NoneType’ object is not callable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unable to understand why this is the case.
I am simply calling the functions – f1, f2 and f3 using f1(), f2() and f3(). I expect to get ‘running f1()’ etc printed out, but instead i get an error.

Could someone please elaborate why this is the case. Thanks.

>Solution :

register annotation is wrapping the functions, it’s basically the same as doing

register(f1)

and since register doesn’t have return statement it returns None, so f1() is actually an attempt to invoke None as a function.

You can solve it by adding return func to register

def register(func):
    print(f'running registry -> {func}')
    registry.append(func)
    return func
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading