Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 833
orokusaki Avatar asked Feb 04 '10 21:02

orokusaki


People also ask

How do you call a method in a string name?

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.

How do you call a function by its string name in Python?

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 ' + '.

How do you call the __ str __ method?

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.

What is the purpose of the __ str __ method?

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.


1 Answers

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!
like image 77
John La Rooy Avatar answered Sep 19 '22 15:09

John La Rooy