Created
May 11, 2015 21:48
-
-
Save nicoguaro/e52029a39fc22d4f35de to your computer and use it in GitHub Desktop.
Evaluate a function with variable number of parameters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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