0

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!

4
  • 2
    class CSVFileFactory: no. Python is not Java. This should just be a function. A class with a single staticmethod should just be a function Commented Dec 23, 2022 at 9:02
  • 1
    In any case, there is nothing really wrong with your if...elif. Commented Dec 23, 2022 at 9:03
  • You could maybe try to extract the type with a regex and use a dict instead, but I don't think that really gives you much of an advantage Commented Dec 23, 2022 at 9:09
  • Thank you! I'm not used to factory methods and that is what I found online, I just thought it was the "right way to do it". Thanks again! Commented Dec 23, 2022 at 9:15

1 Answer 1

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.