How would you build a simple factory in Python without a long if-elif chain?
Keep a dictionary that maps names to classes and look the class up. Adding a new type is a one-line registration rather than another elif branch.
Explain it simply
A railway enquiry counter has a board listing "train name -> platform". The staff do not reason it out each time; they look it up. A dictionary of classes is that board for your factory.
Example
class PdfExporter:
def export(self, data): return f"PDF({data})"
class CsvExporter:
def export(self, data): return f"CSV({data})"
EXPORTERS = {
"pdf": PdfExporter,
"csv": CsvExporter,
}
def make_exporter(kind):
try:
return EXPORTERS[kind]()
except KeyError:
raise ValueError(f"unknown exporter: {kind}")
print(make_exporter("pdf").export("report")) # PDF(report)
print(make_exporter("csv").export("report")) # CSV(report)
EXPORTERS["json"] = type("JsonExporter", (), {"export": lambda self, d: f"JSON({d})"})
print(make_exporter("json").export("report")) # JSON(report)Classes are objects in Python, so they can be stored in a dictionary and called later. Plugins can register themselves without editing the factory function.
What to say in the interview
"I use a registry dictionary from key to class, and instantiate from it. It removes the branching chain, gives a clear error for unknown keys, and lets new types register themselves, which fits the Open/Closed Principle."
Common mistakes
- Silently returning None for unknown keys. Raise a clear error.