1

My program needs to select a class based on user input.

The classes have the same set of methods (inherited from the same ABC) with different implementations. And there are probably more than 30 classes.

# myABC.py
class myABC(ABC):
  @abstractmethod
  def foo():
    pass

# A.py
class A(myABC.myABC):
 def foo():
  print("A")

# B.py
class B(myABC.myABC):
 def foo():
  print("B")

I have only one way in my mind is using if-else. But that is obviously not a great option with more than 30 if, elif statements

# main.py

def get_obj(usr_input: str):
  if usr_input == "A":
    return A.A()
  elif usr_input == "B":
    return B.B()
  ...

Are there any other ways that can solve this problem? Thanks a lot.

2 Answers2

0

Maybe dynamic import can help you.

#importlib.import_module

You should ensure your file name and class name.

Then you can

import importlib

def get_obj(usr_input: str):
    mod = importlib.import_module(usr_input)
    usr_class = getattr(mod, usr_input)
    return usr_class() 

Above assump that your subclass's file name and class name are same as usr_input

hstk
  • 163
  • 2
  • 10
0

If you want to remove the logic from the main script, you could just create a Factory class that contains all the logic for the instantiation.

This way the logic for the instantiation would be decoupled from the main logic.

Also, if you are using python 3.10 or higher, you should use a match statement instead of multiple if else

Fran Arenas
  • 639
  • 6
  • 18