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?

1

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

4 Comments

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)?
That's right. The function is exactly as it is defined in its respective module, so args can be passed as required.
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
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
1

You could use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.