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
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