Python: How do you call a method when you only have the string name of the method?

api, json, python, serialization

Solution

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!

Problem

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) ```

Original source

Related problems