Search code examples
python-3.xmethodsgetattr

Execute python method from a string


I have a string that has the method name and value in it. Currently, I'm using the following implementation which works but doesn't seem elegant. Is there a better way to implement this?

class ObjectResolver:

    def methodResolver(self, value):
        """Some logic here"""
        print(value)


objectResolver = ObjectResolver()

channel = 'methodResolver(helloWorld)'

findValue = channel.strip().find('(')
objectMethod = channel.strip()[:findValue]
attribute = channel.strip()[findValue:][1:-1]

channelResolver = getattr(objectResolver, objectMethod)(attribute)

Output:

helloWorld

Solution

  • The best method I found is to use eval here and specifically to my question above, the implementation is as follows:

    class ObjectResolver:
    
        def methodResolver(self, value):
            """Some logic here"""
            print(value)
    
    
    objectResolver = ObjectResolver()
    
    channel = "methodResolver('helloWorld')"
    handlers = dict(methodResolver=objectResolver.methodResolver)
    eval(channel, handlers)