Skip to content

Instantly share code, notes, and snippets.

@cosmoscalibur
Created September 30, 2013 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosmoscalibur/6768930 to your computer and use it in GitHub Desktop.
Save cosmoscalibur/6768930 to your computer and use it in GitHub Desktop.
If you need a function with arbitrary args you can use kwargs dictionary and exec statement over its items. If 'f' is not a builtin function you need to add from module import function in this auxiliar module.
def eval_fun(f, **args):
''' (str, dict) -> object
f: Function as string.
args: dictionary with arbitrary variables.
Use arbitrary args in **args to eval general functions.
Examples:
>> eval_fun('x**2',x=5)
25
>> eval_fun('x*y', x=3, y=2)
6
'''
for key in args.keys():
exec(str(key)+'='+str(args[key]))
return eval(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment