Answer the question
In order to leave comments, you need to log in
How to execute a function if its name and arguments are contained in a string variable?
The problem is that the functions that I need to call are in other modules, which means that their call will be something like this "package_name.function_name(arg1, arg2, arg3)" (this is given that I imported the module as package_name, and I have 5 modules imported under different names), how can I get this string and call the function directly and pass all the necessary arguments to it? getattr () tried, it does not see functions with arguments. and please don't tell me about parsing, I can parse it, I don't know how to run it.
Answer the question
In order to leave comments, you need to log in
import ast
def parse(s):
last_dot_pos = s.rindex('.')
first_bracket_pos = s.index('(')
pkg_name = s[:last_dot_pos]
f_name = s[last_dot_pos+1:first_bracket_pos]
args = ast.literal_eval(s[first_bracket_pos+1:-1])
return pkg_name, f_name, args
pkg_name, f_name, args = parse('some_package.some_func(3, 5)')
m = __import__(pkg_name)
f = getattr(m, f_name)
f(*args)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question