-
-
Save pratikmallya/6771130 to your computer and use it in GitHub Desktop.
| # Test decorator functionality in Python | |
| def log(F): | |
| def print_args(*args, **kwargs): | |
| print args, kwargs | |
| return print_args | |
| @log | |
| def holy_smokes(a, b, c): | |
| print a + b + c | |
| if __name__ == "__main__": | |
| holy_smokes(1,2,3) |
Question: how are the args of holy_smokes being printed, when there is no clear relation between that and print_args? I cannot see how this works, using my standard view of functions: clearly, log is given an input argument holy_smokes, so we should substitute holy_smokes instead of F in the function definition. And what is
returned? A different function! This new function does only one thing: prints out values of its input arguments. It has no relation to the input function F!
So there's nothing mysterious going on here. You're just making the same mistake repeatedly of not being able to distinguish between function definition and function call!
Nice Resources on Decorators:
http://www.siafoo.net/article/68
http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
Now, according to PEP-318, this leads to the function transformation
to
What took me a long time to understand was that this was a function transformation. My confusion can be clarified by comparing it to what its not:
In this case, the return value is passed to log, whereas in the previous case the function itself was passed.