Skip to content

Instantly share code, notes, and snippets.

@nicoguaro
Created May 11, 2015 21:48
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 nicoguaro/e52029a39fc22d4f35de to your computer and use it in GitHub Desktop.
Save nicoguaro/e52029a39fc22d4f35de to your computer and use it in GitHub Desktop.
Evaluate a function with variable number of parameters.
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)
if __name__=="__main__":
import doctest
doctest.testmod(verbose=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment