Skip to content

Instantly share code, notes, and snippets.

@matthewryanscott
Created March 5, 2013 23:17
Show Gist options
  • Save matthewryanscott/5095280 to your computer and use it in GitHub Desktop.
Save matthewryanscott/5095280 to your computer and use it in GitHub Desktop.
Programmatically creating functions
# This could be called a "function factory".
# It is a function that creates, then returns, new functions.
def generic_site_fn(url_template):
# Define an inner function ...
def generic_site_submit(url):
generic_site_url = url_template.format(url=url)
requests.get(generic_site_url)
# ... that is returned by the factory function.
return generic_site_submit
# These variables become functions.
site1_submit = generic_site_fn('http://site1.com/?page={url}')
site2_submit = generic_site_fn('http://site2.com/submit/?page={url}')
# The above is basically the same as doing this.
# The above is much more readable as far as its intent,
# and much more scalable when you add more to the list.
def site1_submit(url):
url_template = 'http://site1.com/?page={url}'
generic_site_url = url_template.format(url=url)
requests.get(generic_site_url)
def site2_submit(url):
url_template = 'http://site2.com/submit/?page={url}'
generic_site_url = url_template.format(url=url)
requests.get(generic_site_url)
# Example of using individual functions.
url = 'http://mysite.com/mypage.html'
site1_submit(url)
site2_submit(url)
# Let's say we don't care about the individual names.
# We want to just put a bunch of functions in a list.
site_submit_fns = []
# For these generic sites, just convert a list of strings ...
generic_url_templates = [
'http://site1.com/?page={url}',
'http://site2.com/submit/?url={url}',
]
# ... to a list of functions using those strings as URL templates.
site_submit_fns += [generic_site_fn(url_template) for url_template in generic_url_templates]
# You might add other customized functions to the list here
@site_submit_fns.append
def custom_submit(url):
# ... code for custom submit process ...
# ...
# Now loop over the list of functions.
url = 'http://mysite.com/mypage.html'
for site_submit in site_submit_fns:
site_submit(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment