[SOLVED] Using a string in function name during call in python

Issue

I want to call two functions inside a python function. But that call is dependent on a variable. Both functions have the same function. Is there a way to change the function name using a variable ?

What I have as functions :

def a1_suffix(self,option):
  return "does something"
def a2_suffix(self,option):
  return "does something else"

Then the function that I use to call these functions

def myfunction(self,option):
  somevar = "could be a1 or a2"
  self.somevar+"_suffix"(option)

The last line should be equivalent to :

self.a1_suffix(option) or self.a2_suffix(option)

I tried doing that alone but It doesn’t seem to work. I have a TypeError 'str' not callable

What’s the way to reach this mechanism ?

Solution

Create a dict of your functions and use it to dispatch using somevar:

class MyClass:
    def a1_suffix(self, option):
        return "does something"

    def a2_suffix(self, option):
        return "does something else"

    def myfunction(self, somevar, option):
        functions = {"a1": self.a1_suffix, "a2": self.a2_suffix}
        func = functions[somevar]
        return func(option)

Answered By – AKX

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *