Skip to content

Lesson 7 of 9 · 22m

Creational Patterns: Factories, Builders, and Dependency Injection

Python already has first-class functions and modules, so creational patterns shrink: factory functions beat factory hierarchies, builders are rare, and dependency injection is mostly constructor honesty.

The GoF creational patterns were written for languages where constructors were rigid and objects were hard to substitute. Python has first-class functions, keyword arguments, modules, duck typing, and import-time configuration. Half the pattern catalog collapses into 'pass the thing in.' The remaining half is still useful — just smaller.

Factory functions are usually enough

def make_notifier(settings) -> Notifier:
    if settings.environment == "production":
        return SlackNotifier(token=settings.slack_token)
    return LoggingNotifier()

You do not need NotifierFactory, AbstractNotifierFactory, and NotifierFactoryBuilder because functions are already objects. The factory isolates construction policy: environment detection, credential lookup, fallback behavior. Callers receive the interface and remain ignorant of the concrete class.

Builders are for genuinely telescoping construction

A builder helps when object construction has many optional, ordered, or validated steps:

query = (
    QueryBuilder("events")
    .where("created_at >= ?", start)
    .where("tenant_id = ?", tenant_id)
    .order_by("created_at", descending=True)
    .limit(500)
    .build()
)

If the final object has three arguments, a builder is theater. If it has fifteen optional clauses and invalid intermediate states, a builder can keep construction readable and produce one validated object at the end. In Python, keyword-only constructors often cover the same ground with less machinery.

Dependency injection is constructor honesty

class InvoiceService:
    def __init__(self, repo, payments, clock):
        self.repo = repo
        self.payments = payments
        self.clock = clock

That is dependency injection. No container required. The service declares what it needs, tests pass fakes, production passes real implementations. Framework containers become useful when object graphs are large and lifetimes matter — scoped sessions, singletons, per-request resources. A container that merely hides constructor arguments makes the system harder to trace.

Singletons are usually module-level state in a trench coat

Python modules are already singletons per interpreter. Before implementing a Singleton metaclass, ask whether a module-level instance or explicit object passed through the application would do. Global singletons hurt tests, concurrency, and configuration reloads. Most 'we need one instance' claims really mean 'we need one coordination point,' which can still be injected.

Field notes

  • Factory functions should return narrow interfaces or protocols, not leak concrete types across the app.
  • Build objects fully initialized; half-constructed objects are a bug farm.
  • Pass configuration values explicitly at application composition boundaries instead of importing settings deep in libraries.
  • If tests need monkeypatching constructors inside the unit under test, the design is missing dependency injection.

Was this lesson helpful?

Sign in to rate