Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created August 26, 2012 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaha/3479054 to your computer and use it in GitHub Desktop.
Save amitsaha/3479054 to your computer and use it in GitHub Desktop.
Using getattr() to construct function objects from strings
def color_red():
return 'I am red'
def color_green():
return 'I am green'
def color_blue():
return 'I am blue'
#!/usr/bin/python
# Demo of constructing function object from strings
from __future__ import print_function
# module where the functions are defined
import funcs
# entry point when executed
if __name__=='__main__':
colors = ['red','blue','green']
for color in colors:
funcname = 'color_{0:s}'.format(color)
print(getattr(funcs,funcname)())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment