Skip to content

Latest commit

 

History

History

factory-method-python

Folders and files

README.md

The Factory Method Pattern and Its Implementation in Python

This folder provides the code examples for the Real Python tutorial The Factory Method Pattern and Its Implementation in Python.

Setup

The examples run on Python 3.10 or later. Create and activate a virtual environment, then install the pinned dependencies:

$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt

Only the YAML serializer needs PyYAML. Everything else uses the standard library.

Usage

Each folder holds the modules for one part of the tutorial. Run the scripts from inside their folder, because the modules import each other by name:

  • song_serializer/original/: the SongSerializer with complex conditional code, from Introducing Factory Method
  • song_serializer/refactored/: the same serializer refactored to Factory Method, from Basic Implementation of Factory Method
  • object_serializer/: the ObjectSerializer with the SerializerFactory object factory and the YAML format, from An Object Serialization Example through Supporting Additional Formats
  • music_services/: the general purpose ObjectFactory and the specialized MusicServiceProvider, from A General Purpose Object Factory onward
$ cd song_serializer/original/
$ python demo.py
'{"id": "1", "title": "Water of Love", "artist": "Dire Straits"}'
'<song id="1"><title>Water of Love</title><artist>Dire Straits</artist></song>'
ValueError: YAML
$ cd object_serializer/
$ python demo.py
$ cd music_services/
$ python program.py