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)
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.
String To Function Using The eval() Function In Python We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ' () ' separated by the addition symbol ' + '.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
For methods of instances, use getattr
>>> class MyClass(object):
... def sayhello(self):
... print "Hello World!"
...
>>> m=MyClass()
>>> getattr(m,"sayhello")()
Hello World!
>>>
For functions you can look in the global dict
>>> def sayhello():
... print "Hello World!"
...
>>> globals().get("sayhello")()
Hello World!
In this case, since there is no function called prove_riemann_hypothesis
the default function (sayhello
) is used
>>> globals().get("prove_riemann_hypothesis", sayhello)()
Hello World!
The 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
>>> json_functions={}
>>> def make_available_to_json(f):
... json_functions[f.__name__]=f
... return f
...
>>> @make_available_to_json
... def sayhello():
... print "Hello World!"
...
>>> json_functions.get("sayhello")()
Hello World!
>>> json_functions["sayhello"]()
Hello World!
>>> json_functions.get("prove_riemann_hypothesis", sayhello)()
Hello World!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With