What is the best practice for creating an object based on the value of a string argument?
I am loading my configuration from a file and passing the string as an argument that gets mapped to a specific OCR engine subclass constructor. Each class in the code block below My current solution is to use a dictionary and create the object based on the kwargs that are passed into it. Is this a design issue? Should I refactor my inheritance hierarchy to use composition instead of inheritance? I'm looking for any thoughts.
I feel this passing of a string negates the point of polymorphism. For anyone who has any books or docs on design patterns that address issues like this, please send them my way.
Please ignore the lack of error checking - this is only a snippet.
def main(): config_data = load_config(config_path_file) preprocessing_settings = config_data["preprocessing"] engine_name = preprocessing_settings["ocr_engine"] engine_config_args = parse_args(preprocessor(f'{engine_name}-settings')) with create_ocr_engine(engine_name, engine_config_args) as engine: engine.batch_load_from_dir(data_path) engine.process_all() documents = (engine.document_from_batch() .to_json()) def create_ocr_engine(name, kwargs) -> OcrEngine: return # instance of specified subclass based on name and kwargs # # class TesseractOcrEngine(OcrEngine): # pass # class DeepSeekOcrEngine(OcrEngine): # pass # class EasyOcrEngine(OcrEngine): # pass
type()function to construct them. Optionally, you can use a dictionary to return the same class every time the same constructor parameter are used.