-2

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
  • 1
    There are [`eval`](https://docs.python.org/3/library/functions.html#eval) and [`exec`](https://docs.python.org/3/library/functions.html#exec). – Asocia Jul 29 '20 at 17:26
  • @Asocia I have tried exec, It needs my whole class to be inside a string, from what I understood. But the issue is I'm using the class at other places also. I will checkout eval also. – Anshuman Ghosh Jul 29 '20 at 17:32
  • @Asocia So, I checked out eval also, the issue I found is I have to use `value = helloWorld` and then use `eval(methodResolver(value))` which will give the required output. In such a case, I still have to extract `helloWorld` out and set it to a variable. – Anshuman Ghosh Jul 29 '20 at 17:44
  • 1
    @AnshumanGhosh can you upload a detailed code for class-based usage in exec? Also, I hope you now exec() is very anti-pattern and can expose serious security issues in your application. – Sarmad Jul 29 '20 at 17:48
  • @Sarmad updated the code with better formating to avoid confusion and implemented the eval functionality. – Anshuman Ghosh Jul 29 '20 at 17:58
  • 1
    @Sarmad and @Asocia thank you for the help, I didn't know about `eval`. I have posted the exact answer based on my requirement. – Anshuman Ghosh Jul 29 '20 at 18:15

2 Answers2

0

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

Sarmad
  • 315
  • 1
  • 4
  • 15
0

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)