Search code examples
python-3.xmethods

Python - Better way to run external methods with similar, but different, names?


Currently in my project, I have some code like this in a method, where param1 and param2 are guaranteed to be the same for every function call:

def run_funct(self):

    if self.my_type == "a":
        a_funct(param1, param2)

    if self.my_type == "b":
        b_funct(param1, param2)

    if self.my_type == "c":
        c_funct(param1, param2)

Is there a way in Python to make it more like?

def run_funct(self):

    {self.my_type}_funct(param1, param2)

I've done some research online, but I don't really know what this would be called. It's not really command substitution or variable substitution, right?


Solution

  • Assuming x_functs are defined at module scope, you can do something like this:

    def run_funct(self):
        globals()[f'{self.my_type}_funct'](param1, param2)
    

    But this is pretty gross, maybe rethink your design.