Created
April 29, 2013 06:37
-
-
Save sidchilling/5480027 to your computer and use it in GitHub Desktop.
Script to show how to write a manual decorator
This file contains 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
# Shows how to manually define and use a decorator | |
# A decorator is a function which expects another function as a parameter | |
def my_shiny_new_decorator(a_function_to_decorate): | |
# Inside, the decorator defines a function on the fly: "the wrapper". | |
# This function is going to be wrapped around the original function so it can execute | |
# code before and after the original function | |
def the_wrapper_around_the_original_function(): | |
# Put the code you want to execute BEFORE the original function is called | |
print 'Before the function runs' | |
# Call the original function (with parantheses) | |
a_function_to_decorate() | |
# Put the code you want to execute AFTER the original function is called | |
print 'After the function runs' | |
# At this point, "a_function_to_decorate" HAS NEVER BEEN executed. | |
# We return the "wrapper" function we just created | |
# The wrapper contains the function and the code to execute before and after. | |
# The decorator is then ready to use! | |
return the_wrapper_around_the_original_function | |
# Now imagine you create a function you don't want to touch again | |
def a_stand_alone_function(): | |
print 'I am a stand alone function. Please do not modify me' | |
a_stand_alone_function() | |
print '\n\n' | |
# Outputs: I am a stand alone function. Please do not modify me | |
# Now we will decorate the a_stand_alone_function function. | |
# Just pass it to the decorator and call the returned function and it will | |
# decorating the a_stand_alone_function function. | |
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function) | |
a_stand_alone_function() | |
print '\n\n' | |
# Writing the same thing using the decorator syntax | |
@my_shiny_new_decorator | |
def another_stand_alone_function(): | |
print 'Leave me alone!' | |
# Now call the decorated function directly | |
another_stand_alone_function() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment