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?

Edit: Updated the implementation with eval. Still need to extract helloWOrld from channel.

class ObjectResolver:

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


objectResolver = ObjectResolver()

value = 'helloworld'
eval('objectResolver.methodResolver(value)')
eval('objectResolver.methodResolver')(value)

channel = 'methodResolver(helloWorld)'
findValue = channel.strip().find('(')
objectMethod = channel.strip()[:findValue]
attribute = channel.strip()[findValue:][1:-1]
channelResolver = getattr(objectResolver, objectMethod)(attribute)

Output:

helloWorld

2 answers

  • answered 2020-07-29 17:44 Sarmad

    You can use eval() or exec()

    class ObjectResolver:
    
    def methodResolver(self, value):
        """Some logic here"""
        print(value)
    
    
    objectResolver = ObjectResolver()
    
    // Something like this...
    channel = eval('methodResolver')(helloWorld)
    // OR
    exec('channel = "methodResolver(helloWorld)"')
    
    findValue = channel.strip().find('(')
    objectMethod = channel.strip()[:findValue]
    attribute = channel.strip()[findValue:][1:-1]
    channelResolver = getattr(objectResolver, objectMethod)(attribute)
    

    Learn more about eval and exec

  • answered 2020-07-29 18:10 Anshuman Ghosh

    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)