This folder provides the code examples for the Real Python tutorial The Factory Method Pattern and Its Implementation in Python.
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.txtOnly the YAML serializer needs PyYAML. Everything else uses the standard library.
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/: theSongSerializerwith complex conditional code, from Introducing Factory Methodsong_serializer/refactored/: the same serializer refactored to Factory Method, from Basic Implementation of Factory Methodobject_serializer/: theObjectSerializerwith theSerializerFactoryobject factory and the YAML format, from An Object Serialization Example through Supporting Additional Formatsmusic_services/: the general purposeObjectFactoryand the specializedMusicServiceProvider, 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