2

Let's say I Have a main.py and 26 additional Python files called A.py through Z.py.
The 26 files all contain a single function called functionA(),functionB()...functionZ() I have a variable, let's call it "var" and wanna fire the right function depending on the variable. Right now my main.py Code looks like this:

from A import functionA
from B import functionB
.
.
.
from Z import functionZ

var = "N";

if var == "A":
  functionA()
elif var == "B":
  functionB()
.
.
.
elif var == "Z":
 functionZ()

However the actual code won't just have 26 functions but over a hundred.
I heard that if..elif..elif is more performance efficient than a switch var: would be. However is there any way I could just fire functionvar() depending on the variable without iterating through all of them one by one? If not, is if...elif...elif...else the most efficient way?

RadicalM1nd
  • 147
  • 1
  • 10
  • Possible duplicate of [How to use a variable as function name in Python](https://stackoverflow.com/questions/34794634/how-to-use-a-variable-as-function-name-in-python) – splash58 Oct 25 '19 at 09:27

2 Answers2

2

If you have to adhere to this structure, you can use importlib. It's not very transparent, but achieves what you want in a small number of lines and doesn't need all the imports at the top of the file.

import importlib

var = 'A'

module = importlib.import_module(var)  # imports module A

f_name = f"function{var}"  # = 'functionA'

f_to_call = getattr(module, f_name)  # the function as a callable

result = f_to_call()  # calls A.functionA()
  • This seems like a good solution as it cuts out the imports too, thank you! If I wanted to pass some parameters to the function, where would I do so? Would it be `result = f_to_call(param1, param2)`? – RadicalM1nd Oct 25 '19 at 09:46
  • 1
    That's right. The function is exactly as it is defined in its respective module, so args can be passed as required. – seymourgoestohollywood Oct 25 '19 at 10:25
  • Perfect, thanks! One last question: If I have all the additional files in a folder Folder/A.py and so on, how would the import_module() function be called correctly? I looked around a bit and found things like `importlib.import_module(var , 'Folder')` with or without the 's. But none of it seems to work – RadicalM1nd Oct 25 '19 at 10:29
  • 1
    `importlib.import_module` takes a single string in the format that you could actually reference the module. so if you would have imported like `from Folder import A`, you would use `importlib.import_module(f"Folder.{var}")` as `f"Folder.{var}" == Folder.A` – seymourgoestohollywood Oct 25 '19 at 10:36
1

You could use:

locals()['function'+var]()

lainatnavi
  • 1,453
  • 1
  • 14
  • 22