If you are accepting data from the user, for security reasons, it is probably best to use a manual dict that only accepts a well-defined set of valid user inputs:
unpack_options = { 'unpack_pdb_line' : unpack_pdb_line, 'unpack_pdb_line2' : unpack_pdb_line2, }
Ignoring security for a moment, we note in passing that a simple way to go from (variable name string) to (value that the variable name refers to) is to use the global variables () builtin dict:
unpack_function=globals()['unpack_pdb_line']
Of course, this will only work if the unpack_pdb_line variable is in the global namespace.
If you need to get into a package for a module or module for a variable, then you can use this function
import sys def str_to_obj(astr): print('processing %s'%astr) try: return globals()[astr] except KeyError: try: __import__(astr) mod=sys.modules[astr] return mod except ImportError: module,_,basename=astr.rpartition('.') if module: mod=str_to_obj(module) return getattr(mod,basename) else: raise
You can use it as follows:
str_to_obj('scipy.stats') # <module 'scipy.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/__init__.pyc'> str_to_obj('scipy.stats.stats') # <module 'scipy.stats.stats' from '/usr/lib/python2.6/dist-packages/scipy/stats/stats.pyc'> str_to_obj('scipy.stats.stats.chisquare') # <function chisquare at 0xa806844>
It works for nested packages, modules, functions, or (global) variables.
source share