Skip to content

Instantly share code, notes, and snippets.

@pratikmallya
Last active December 24, 2015 08:29
Show Gist options
  • Save pratikmallya/6771130 to your computer and use it in GitHub Desktop.
Save pratikmallya/6771130 to your computer and use it in GitHub Desktop.
This piece of code is what I'm using to clarify certain function-related concepts in Python, especially those relating to decorators
# 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)
@pratikmallya
Copy link
Author

Now, according to PEP-318, this leads to the function transformation

@log
def holy_smokes():
    pass

to

def holy_smokes():
    pass
holy_smokes = log(holy_smokes)

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:

holy_smokes = log(holy_smokes(1,2,3))

In this case, the return value is passed to log, whereas in the previous case the function itself was passed.

@pratikmallya
Copy link
Author

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!

@pratikmallya
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment