This tutorial explores the Factory Method design pattern and its implementation in Python. Design patterns became a popular topic in the late 1990s after the so-called Gang of Four (GoF: Gamma, Helm, Johnson, and Vlissides) published their book Design Patterns: Elements of Reusable Object-Oriented Software.
The book describes design patterns as a core design solution to recurring problems in software and classifies each design pattern into categories according to the nature of the problem. Each pattern is given a name, a problem description, a design solution, and an explanation of the consequences of using it.
The GoF book describes Factory Method as a creational design pattern. Creational design patterns are related to the creation of objects, and Factory Method is a design pattern that creates objects with a common interface.
This is a recurrent problem that makes Factory Method one of the most widely used design patterns, so it’s worth understanding it well and knowing how to apply it.
By the end of this tutorial, you’ll understand that:
- Factory Method is a creational design pattern that separates creating an object from the code that uses it.
- The pattern has three components: a client that needs an object, a creator that decides which concrete implementation to build, and the product interface that those implementations share.
- An
if/elif/elsechain that picks which object to build is a typical opportunity to refactor toward Factory Method. - An object factory with a registration method lets you add new implementations, such as a new serialization format, without changing existing code.
- A general purpose
ObjectFactoryaccepts any callable as a builder, so it can create objects that need different initialization steps.
Along the way, you’ll refactor a small serializer step by step, so you can see each component of the pattern appear in the code. Then you’ll generalize the idea into a reusable object factory and apply it to a music service example.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Take the Quiz: Test your knowledge with our interactive “The Factory Method Pattern and Its Implementation in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
The Factory Method Pattern and Its Implementation in PythonCheck your grasp of the Factory Method pattern in Python: when to use it, the roles involved, and how to implement a flexible object factory.
Get Your Code: Click here to download the free sample code you’ll use to refactor a serializer and build a general purpose object factory.
Object-Oriented Python Live Course: Want to practice design patterns like this one in a real project? In Real Python’s Object-Oriented Python live course, you build a complete simulator with an instructor and design classes that feel native to the language. Join the waitlist to hear about the next dates.
Introducing Factory Method
Factory Method is a creational design pattern used to create concrete implementations of a common interface.
It separates the process of creating an object from the code that depends on the interface of the object.
For example, an application requires an object with a specific interface to perform its tasks. The concrete implementation of the interface is identified by some parameter.
Instead of using a complex if/elif/else conditional structure to determine the concrete implementation, the application delegates that decision to a separate component that creates the concrete object. With this approach, the application code is simplified, making it more reusable and easier to maintain.
Imagine an application that needs to convert a Song object into its string representation using a specified format. Converting an object to a different representation is often called serializing. You’ll often see these requirements implemented in a single function or method that contains all the logic and implementation, like in the following code:
# In serializer_demo.py import json import xml.etree.ElementTree as et class Song: def __init__(self, song_id, title, artist): self.song_id = song_id self.title = title self.artist = artist class SongSerializer: def serialize(self, song, format): if format == "JSON": song_info = { "id": song.song_id, "title": song.title, "artist": song.artist, } return json.dumps(song_info) elif format == "XML": song_info = et.Element("song", attrib={"id": song.song_id}) title = et.SubElement(song_info, "title") title.text = song.title artist = et.SubElement(song_info, "artist") artist.text = song.artist return et.tostring(song_info, encoding="unicode") else: raise ValueError(format) In the example above, you have a basic Song class to represent a song and a SongSerializer class that can convert a song object into its string representation according to the value of the format parameter.
The .serialize() method supports two different formats: JSON and XML. Any other format specified is not supported, so a ValueError exception is raised.
You can use the Python interactive shell to see how the code works:
>>> import serializer_demo as sd >>> song = sd.Song("1", "Water of Love", "Dire Straits") >>> serializer = sd.SongSerializer() >>> serializer.serialize(song, "JSON") '{"id": "1", "title": "Water of Love", "artist": "Dire Straits"}' >>> serializer.serialize(song, "XML") '<song id="1"><title>Water of Love</title><artist>Dire Straits</artist></song>' >>> serializer.serialize(song, "YAML") Traceback (most recent call last): ... ValueError: YAML You create a song object and a serializer, and you convert the song to its string representation by using the .serialize() method. The method takes the song object as a parameter, as well as a string value representing the format you want. The last call uses YAML as the format, which is not supported by the serializer, so a ValueError exception is raised.
This example is short and simplified, but it still has a fair amount of complexity. There are three logical or execution paths depending on the value of the format parameter. This may not seem like a big deal, and you’ve probably seen code with more complexity than this, but the above example is still pretty hard to maintain.
The Problems With Complex Conditional Code
Read the full article at https://realpython.com/factory-method-python/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

