@decorators in Python: why the inner defined function? -
i'm starting python , have been exposed decorators. wrote following code, mimicking seeing, , works:
def decorator_function(passed_function): def inner_decorator(): print('this happens before') passed_function() print('this happens after') return inner_decorator @decorator_function def what_we_call(): print('the actual function called.') what_we_call()
but wrote this, throws errors:
def decorator_function(passed_function): print('this happens before') passed_function() print('this happens after') @decorator_function def what_we_call(): print('the actual function called.') what_we_call()
so, why need have inner nested function inside decorator function? purpose serve? wouldn't simpler use syntax of second? not getting?
the funny thing both have same (correct) output, second on has error text well, saying "typeerror: 'nonetype' object not callable"
please use language , examples suitable starting python, first programming language - , new oop well! :) thanks.
the reason when wrap what_we_call in decorator_function doing:
@decorator_function def what_we_call(): ...
what you're doing is:
what_we_call = decorator_function(what_we_call)
in first example works because don't run inner_function actually, initialise it, , return new inner_function (that call later when call decorated what_we_call):
def decorator_function(passed_function): def inner_decorator(): print('this happens before') passed_function() print('this happens after') return inner_decorator
contrarily, in second example you're going run 2 print statements , passed_function (what_we_call in our case) in between:
def decorator_function(passed_function): print('this happens before') passed_function() print('this happens after')
in other words, don't return function in example of before:
what_we_call = decorator_function(what_we_call)
you run code (and see output), decorator_function returns 'none' what_we_call (overwriting original function), , when call 'none' if function python complains.
Comments
Post a Comment