This is for use in a JSON API.
I don’t want to have:
if method_str == 'method_1':
method_1()
if method_str == 'method_2':
method_2()
For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in arguments to the called functions).
Here is an example:
INCOMING JSON:
{
'method': 'say_something',
'args': [
135487,
'a_465cc1'
]
'kwargs': {
'message': 'Hello World',
'volume': 'Loud'
}
}
# JSON would be turned into Python with Python's built in json module.
Resulting call:
# Either this
say_something(135487, 'a_465cc1', message='Hello World', volume='Loud')
# Or this (this is more preferable of course)
say_something(*args, **kwargs)
For methods of instances, use
getattrFor functions you can look in the global dict
In this case, since there is no function called
prove_riemann_hypothesisthe default function (sayhello) is usedThe problem with this approach is that you are sharing the namespace with whatever else is in there. You might want to guard against the json calling methods it is not supposed to. A good way to do this is to decorate your functions like this