The Factory Pattern in Python: Delegating Object Creation

This article explains how factories centralize the choice of which class to instantiate in Python, from mappings and self-registering classes to the Factory Method pattern and classmethod constructors, together with their common pitfalls.

A bright green snake with white markings coiled around a pale branch, its head resting on its own coils against a dark background.
Photo by Haim Charbit on Unsplash

Code that must choose which class to instantiate often grows a chain of if and elif statements, one branch per class, and every new class forces a new branch in every place where the choice is made. The present article addresses the factory, the design idea that moves that decision to a single place, so that the code which uses an object no longer needs to know which concrete class produced it. It distinguishes the simple factory, a function or mapping that returns the right object, from the Factory Method of the classic catalogue of design patterns, in which subclasses decide what to create, and it shows the forms that Python itself uses in its standard library. In Python, every class is already a callable that creates its own instances, and this is the secret weapon that makes most factories a few lines long.

A Mapping from Names to Classes

Since classes are ordinary objects, they can be stored in a dictionary and called later, which replaces the chain of conditions with a single lookup. The following example exports a list of records to JSON or CSV, both written in memory, and chooses the exporter by name.

import csv
import io
import json

class JsonExporter:
    def export(self, rows):
        return json.dumps(rows)

class CsvExporter:
    def export(self, rows):
        buffer = io.StringIO()
        writer = csv.DictWriter(buffer, fieldnames=list(rows[0]), lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)
        return buffer.getvalue()

EXPORTERS = {"json": JsonExporter, "csv": CsvExporter}

def create_exporter(kind):
    try:
        exporter_class = EXPORTERS[kind]
    except KeyError:
        known = ", ".join(sorted(EXPORTERS))
        raise ValueError(f"unknown format {kind!r}; expected one of: {known}") from None
    return exporter_class()

rows = [{"name": "Ada", "score": 9}, {"name": "Alan", "score": 8}]
print(create_exporter("json").export(rows))
# Output: [{"name": "Ada", "score": 9}, {"name": "Alan", "score": 8}]
print(create_exporter("csv").export(rows), end="")
# Output: name,score
# Output: Ada,9
# Output: Alan,8
try:
    create_exporter("xml")
except ValueError as error:
    print(error)  # Output: unknown format 'xml'; expected one of: csv, json

The calling code depends only on the method export, which both classes provide, and never names JsonExporter or CsvExporter. This arrangement is usually called a simple factory; it is not one of the patterns of the classic catalogue, but a convenient step towards them. The translation of the error matters as much as the lookup: without it, an unknown format raises a bare KeyError: 'xml', which tells the caller nothing about the formats that exist.

Registering Products Without Editing the Factory

A mapping written by hand must still be edited whenever a class is added. The hook __init_subclass__, available since Python 3.6 (PEP 487), runs every time a class is subclassed, so each new class can register itself at the moment it is defined, a technique compared with metaclasses in the article devoted to metaclasses.

import json

class Exporter:
    registry = {}

    def __init_subclass__(cls, *, format_name, **kwargs):
        super().__init_subclass__(**kwargs)
        Exporter.registry[format_name] = cls

    @classmethod
    def create(cls, format_name):
        return Exporter.registry[format_name]()

class JsonExporter(Exporter, format_name="json"):
    def export(self, rows):
        return json.dumps(rows)

class LinesExporter(Exporter, format_name="lines"):
    def export(self, rows):
        return "\n".join(str(row) for row in rows)

print(sorted(Exporter.registry))                                # Output: ['json', 'lines']
print(Exporter.create("lines").export([1, 2, 3]).split("\n"))  # Output: ['1', '2', '3']

The keyword format_name in each class statement is passed to __init_subclass__, which records the class under that name; the factory method create never changes when a format is added. A class is registered, however, only when the module that defines it is imported. Applications that accept plug-ins from other packages therefore publish their classes as entry points and load them with importlib.metadata.entry_points(group=...), a selection by group available since Python 3.10.

The Factory Method: Subclasses Decide What to Create

The Factory Method pattern, described in 1994 in the classic catalogue of design patterns, places the creation in a method of a base class that subclasses override. Real-time strategy games offer a precise image of this structure: the player gives the same order, to train a unit, to any production building, but a barracks produces infantry and an airfield produces aircraft, because each building decides what the order creates. This means that the base class fixes when the object is created and how it is used, whereas each subclass decides which class is instantiated. The analogy, however, stops at this point, because the buildings of a game are fixed by its designers, whereas a new subclass can be added by any module without changing the base class.

import json
from abc import ABC, abstractmethod

class Report(ABC):
    def __init__(self, rows):
        self.rows = rows

    @abstractmethod
    def create_exporter(self):
        """Factory method: each subclass decides which exporter to build."""

    def render(self):
        exporter = self.create_exporter()
        return f"{len(self.rows)} rows -> {exporter.export(self.rows)}"

class JsonExporter:
    def export(self, rows):
        return json.dumps(rows)

class UpperExporter:
    def export(self, rows):
        return " | ".join(str(row).upper() for row in rows)

class JsonReport(Report):
    def create_exporter(self):
        return JsonExporter()

class ShoutingReport(Report):
    def create_exporter(self):
        return UpperExporter()

for report in (JsonReport(["a", "b"]), ShoutingReport(["a", "b"])):
    print(report.render())
# Output: 2 rows -> ["a", "b"]
# Output: 2 rows -> A | B

The method render is written once in Report and works with any exporter that a subclass returns, which satisfies the open/closed principle: the hierarchy is open to new reports and closed to modifications of render. Declaring create_exporter abstract makes a subclass that forgets it fail at instantiation, as explained in the article devoted to abstract base classes. In Python, the same flexibility is often obtained without a hierarchy, by passing the class itself as an argument, for example Report(rows, exporter_factory=JsonExporter), since any callable that returns an object can play the role of the factory.

Alternative Constructors with classmethod

The most common factory in Python is a class method that builds an instance from another representation of the data. The standard library uses it widely: date.fromisoformat, datetime.fromtimestamp and dict.fromkeys are all class methods.

from datetime import date

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

class LabTemperature(Temperature):
    pass

reading = LabTemperature.from_fahrenheit(212)
print(type(reading).__name__, reading.celsius)  # Output: LabTemperature 100.0

print(date.fromisoformat("2025-11-21"))        # Output: 2025-11-21
print(dict.fromkeys(["a", "b"], 0))            # Output: {'a': 0, 'b': 0}

Because the method receives the class through cls and calls it, the constructor inherited by LabTemperature returns a LabTemperature, not a Temperature. A class can offer several such constructors with descriptive names, whereas __init__ can have only one signature.

Pitfalls of Factories

A factory centralizes creation, so its mistakes are repeated in every object it produces. Five pitfalls are distinguished, which are the following:

  1. Opaque errors. A lookup without translation exposes a KeyError that does not list the valid names.
  2. Instances instead of classes. A mapping that stores an instance returns the same object to every caller, which then share its state.
  3. Hard-coded classes. A class method that calls the class by name, instead of cls, returns the base class even when it is called on a subclass.
  4. Registration depends on imports. A self-registering class that lives in a module never imported does not exist for the factory.
  5. Factories for everything. A creator hierarchy for a class that has a single implementation adds indirection without flexibility; calling the class directly is clearer.

The second and third pitfalls are reproduced in the following example.

class Collector:
    def __init__(self):
        self.items = []

SHARED = {"collector": Collector()}   # an instance, not a class
FRESH = {"collector": Collector}      # the class itself

first = SHARED["collector"]
second = SHARED["collector"]
first.items.append("x")
print(second.items, first is second)  # Output: ['x'] True

third = FRESH["collector"]()
fourth = FRESH["collector"]()
third.items.append("x")
print(fourth.items, third is fourth)  # Output: [] False

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    @classmethod
    def origin(cls):
        return Point(0, 0)   # hard-coded class instead of cls

class Point3D(Point):
    pass

print(type(Point3D.origin()).__name__)  # Output: Point

The shared instance looks like a factory but behaves as a global variable, and the hard-coded constructor silently loses the subclass; both errors are corrected by storing and calling the class, cls in the case of a class method.

Choosing a Form of Factory

Consequently, the right form depends on who decides the class and when, as the following table summarizes.

Situation Recommended approach
A single class, always the same Call the class directly
The class is chosen from a name in data or configuration A mapping from names to classes, with a clear error
New classes must appear without editing the mapping Registration with __init_subclass__
Classes provided by other installed packages Entry points loaded with importlib.metadata
A base class fixes the workflow and subclasses choose the product Factory Method with an abstract method
Building an instance from another representation A classmethod constructor that calls cls
The algorithm, not the object, must vary The Strategy pattern

A factory decides which object exists, whereas a strategy decides which behaviour runs, and the two are frequently combined, a relation visible in the article devoted to the Strategy pattern.

Conclusion

It is concluded that a factory gathers in one place the decision of which class to instantiate, and that Python reduces most factories to a mapping of classes, a registry filled by __init_subclass__ or a class method that calls cls, while the Factory Method remains the appropriate form when a base class must fix the workflow and leave the product to its subclasses. This magic rests on the fact that classes are callable objects, and it fails only when instances are shared, classes are hard-coded or errors are left opaque. Every factory ultimately calls a class, and the method that actually allocates each new instance before __init__ runs, __new__, is developed in a future article of this series.