V
V
vvrider2017-09-05 23:09:16
Python
vvrider, 2017-09-05 23:09:16

How to make callable function from json?

How to make callable function from json?
Currently implemented like this:
def _display_help ():
...
commands = {
"help": _display_help,
}
func = commands.get("help")
The commands list got pretty big and wanted to import json via json.loads
But since this kind of json is not valid, it should be "help": " _display_help "
String is not callable object -> it's quite obvious
While there is not enough practical experience, I would like to know how this can be implemented without crutches?
Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2017-09-05
@Eugen_p

Look towards the ast module. There is also a built-in eval function, but it is not very good to use it

M
maxfox, 2017-09-06
@maxfox

Correct option:
1. Make a decorator that registers a function with the desired name in a special dictionary. (like @app.route in Flask)
2. Write the functions you need, register them with this decorator.
3. Call functions from the dictionary by key-string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question