Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Factory Method Suggestions

I would like to ask you to help me out with my factory method. I have to handle multiple and periodic csv objects, each of which has its own properties, thus its own class. The only way I can tell Python one csv differs from another, is due to the file name.
Now, I create different object based on the file name, as follows:

class CSVFileFactory:
     @staticmethod
     def obj_builder(fname: str):
         if "type1" in fname:
             return TypeOneCSV(filename=fname)
         elif "type2" in fname:
             return TypeTwoCSV(filename=fname)
         elif "type3" in fname:
             return TypeThreeCSV(filename=fname)
         ...
         ...

And so on.
Do you think this is the cleanest way I could do it? Are there any conventions I’m not applying?
Do you have any suggestion to reduce code complexity and the never-ending "if-elif" statement?
Thanks a lot for the help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As suggested, a class is not necessary, especially when you just use a static method (BTW: Spelling error in the decorator). If you want a namespace, create a module for it, otherwise just use a function.

For the code itself, you can make a loop if the construction follows the exact same pattern. Might be a bit shorter.

def open_csv_file(fname: str):
    filetypes = (("type1", TypeOneCSV),
                 ("type2", TypeTwoCSV),
                 ("type3", TypeThreeCSV),
    )
    for pattern, classtype in filetypes:
        if pattern in fname:
            return classtype(filename=fname)
    raise ValueError("unknown file type")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading