pythonclassfactory-methodobject-construction

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!


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