Last active
August 29, 2015 14:19
-
-
Save lordkebab/ca26040ceaece6dbd800 to your computer and use it in GitHub Desktop.
Learning about python decorators
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
''' Learning about python decorators ''' | |
def is_logged_in(func): | |
def wrapper(logged_in): | |
print "Checking logged in status..." | |
if logged_in: | |
print "Ok!" | |
func(logged_in) | |
else: | |
print "Not logged in" | |
return wrapper | |
@is_logged_in | |
def display_page(logged_in): | |
print "Displaying page" | |
display_page(1) | |
print '\n' | |
display_page(0) |
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
''' Let's say the API takes a list of arguments as a comma-delimited string, | |
but your wrapper allows you to call a method with a list parameter or comma-delimited string parameter. | |
This decorator will make sure that if it's a list, it formats it to what the API expects before calling the API. | |
''' | |
def format_params(func): | |
def wrapper(params): | |
if type(params) is list: | |
print "Got a list, formatting to string" | |
func(','.join(params)) | |
else: | |
print "Got what I'm supposed to, send it on to the API" | |
func(params) | |
return wrapper | |
@format_params | |
def api_call(params): | |
# printing for demo purposes | |
print params | |
# sending a list | |
api_call(['a','b','c']) | |
print '\n' | |
# sending a comma-delimited string | |
api_call('a,b,c,d') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First file is equivalent to: