N
N
NikClik2018-08-24 07:26:28
Python
NikClik, 2018-08-24 07:26:28

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

2 answer(s)
S
Sergey Gornostaev, 2018-08-24
@NikClik

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)

H
Helow19274, 2018-08-24
@Helow19274

exec('package_name.function_name(arg1, arg2, arg3)')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question