Python - firing a specific function depending on a variable

Viewed 66

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?

2 Answers

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()

You could use:

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

Related