Factory
A factory is a function or method that creates objects so callers do not call a concrete class themselves. In Python that is often a @classmethod alternative constructor or a small function with if/match.
Detailed Explanation
Order("A-1", 2) is a constructor. Order.from_csv_row("A-1,2") is a factory. The caller does not know how the object is allocated, which subclass to pick, or how to parse the input. The factory does.
Python does not have constructor overloads, so class methods that return cls(...) are the standard factory. Using cls instead of the class name keeps subclasses working. A module-level function build_order(data) is the other form, and it can return different types: PriorityOrder vs Order based on a field.
A factory class (OrderFactory) with many methods is useful when creation needs collaborators (a clock, an id generator) you want to inject. If the factory has no state, a function is enough. Java's AbstractFactory hierarchies are rarely worth the extra types in Python.
dict registries are factories: handlers[kind](**payload). Plugins register a class; the factory looks it up. That is simpler than a tree of factory classes.
Factories hide new. They also hide dependencies. A factory that imports a database inside create() is a hidden global. Pass the connection in, or you cannot test the factory without the database.
None as a return for "could not create" forces every caller to check. Raise a specific exception, or return a Result type if you have one. Do not return a half-built object.
Code Examples
class Order:
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty
@classmethod
def from_csv_row(cls, row: str) -> "Order":
sku, qty = row.split(",")
return cls(sku, int(qty))
print(Order.from_csv_row("A-1,2").qty) # 2def payment_from_name(name: str):
kinds = {"card": Card, "wire": Wire}
try:
return kinds[name]()
except KeyError:
raise ValueError(f"unknown payment {name}") from None
class Card:
pass
class Wire:
pass
print(type(payment_from_name("card")).__name__) # CardCommon Gotchas
`return Order(...)` in a classmethod
subclasses get the parent type. Use `cls(...)`.
A factory that talks to the network
inject the client so tests do not hit the network.
Empty `except` around construction
you hide `TypeError` from your own bugs. Catch the specific parse error.
`None` returns spread `if result is None` everywhere
raise or use a sentinel at one boundary.