I want to call a module function with getattr
(or maybe something else?) from a string like this:
import bar
funcStr = "myFunc(\"strParam\", 123, bar.myenum.val1, kwarg1=\"someString\", kwarg2=456, kwarg3=bar.myenum.val2)"
[function, args, kwargs] = someParsingFunction(funcStr)
# call module function
getattr(bar, function)(*args, **kwargs)
How can I extract the args
and kwargs
from the string, so I can pass them to getattr
?
I tried a literal_eval
approach with pythons ast
module. But ast
is not able to evaluate the enums of the module bar
. And all other examples on SO pass a kwargs
map with only strings in it. And they especially never parse the arguments from a string. Or is there another way to directly call the function from the string?
EDIT: A python script reads the function string from file. So using eval
here is not advised.
EDIT2: Using python 3.6.3
EDIT3: Thanks to the first two answers I came up with two ideas. After parsing the args
and kwargs
out of the input string there are two possibilities for getting the right type of the arguments.
- We could use
ast.literal_eval(<value of the argument>)
. For arguments with standard type like inkwarg2
it will return the needed value. If this excepts, which will happen for the enums, then we we will usegetattr
on thebar
module and get the enums. If this excepts as well, then the string is not valid. - We could use the
inspect
module and iterate through the parameters ofmyFunc
. Then for everyarg
andkwarg
we will check if the value is an instance of amyFunc
parameter (type). If so, we will cast the arg/kwarg to themyFunc
parameter type. Otherwise we raise an exception because the given arg/kwarg is not an instance of amyFunc
parameter. This solution is more flexible than the first one.
Both solutions feel more like a workaround. First tests seem to work. I will post my results later here.