Last active
December 15, 2015 10:29
-
-
Save BrianHicks/5246200 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# define our higher-order function | |
def more_verboser(func): | |
def inner(x): | |
val = func(x) | |
print val | |
return val | |
return inner | |
# defined without decorator | |
def double(x): | |
return x * 2 | |
double = more_verboser(double) | |
# so now calling double(2) would print "4" to the console, but the syntax is a | |
# little silly - it's confusing to have obj(other_call)? what? So we do | |
# things a little differently, as a matter of convention: | |
@more_verboser | |
def double(x): | |
return x * 2 | |
# this is EXACTLY the same call as the line starting with `double = ...`, | |
# except it's a nicer SYNTAX. Again, it's purely a syntactical change, so we | |
# call these kind of things "Syntactic Sugar", since it makes the syntax | |
# "sweeter". | |
# This gets even better, since we can put multiple "decorators" on a single | |
# function, which would be really confusing if we had to wrap them manually. | |
@more_verboser | |
@more_verboser | |
def double(x): | |
return x * 2 | |
# so calling that will print the result twice, since the inner functions get | |
# evaluated twice |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment