K
K
Keste ...2018-10-29 00:14:51
Python
Keste ..., 2018-10-29 00:14:51

How to call a function whose name is written in a string in Python 3?

The question is this: I enter the name of the function and I just want this name to execute the function.
And I don't want to create a couple dozen if/elif/else to iterate over all the functions in the code.
I don't know how to do this!
Please describe how to do this in more detail.

call_func = input("Введите название функции чтобы её вызвать: ")
if call_func[0] == '$':
    call_func = call_func[1:]
    call_func()

Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Jock Tanner, 2018-10-29
@Keste

In general, the very formulation of the kagbe question hints at the architectural problems of this approach. But, if you decide the issue "on the forehead", then here is the most logical option:

call_func = input("Введите название функции чтобы её вызвать: ")
locals()[call_func]()

By this I mean that the functions are defined in the same namespace as call_func. If they are defined in the namespace of the module, and call_func- deeper, in a function or method, then globals(). And if they are generally somewhere in other modules that may not be imported in advance, then you need to dig aside importlib.import_module, but this is certainly an overkill.
And, of course, it is not safe to use user input here. Not as dangerous as eval, but also not good.

K
kratorr, 2018-10-29
@kratorr

def func1(text):
    return text

def func2():
    return ""

functions = {'func1':func1, 'func2':func2}

functions['ваш input']()

B
bbkmzzzz, 2018-10-29
@bbkmzzzz

Create a dictionary. The key is a string to define, the value is a function.

def foo():
    print('foo()')

def bar(x):
    print(x)

dc = {'foo': foo, 'bar': bar}
dc['foo']()
dc['bar'](10)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question