Skip to content

Instantly share code, notes, and snippets.

@lordkebab
Last active August 29, 2015 14:19
Show Gist options
  • Save lordkebab/ca26040ceaece6dbd800 to your computer and use it in GitHub Desktop.
Save lordkebab/ca26040ceaece6dbd800 to your computer and use it in GitHub Desktop.
Learning about python decorators
''' 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)
''' 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')
@lordkebab
Copy link
Author

First file is equivalent to:

is_logged_in(display_page(1))

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