Card 06/ 09
Singleton Classes vs Python Modules
A Python module is created once and shared by every import, which is a singleton without a class.
Python runs a module's code once, on the first import, and stores the module object in sys.modules; every later import returns that stored object. So a module is already a single shared instance, and its top-level variables are that instance's state. This card shows the module form beside the class form and says what each one gives up.
import importlib
import sys
from sgconf import settings_module
from sgconf import settings_module as again
later = importlib.import_module("sgconf.settings_module")
print("same module object:", settings_module is again is later)
print("cached in sys.modules:", sys.modules["sgconf.settings_module"] is settings_module)
print("currency:", settings_module.values["currency"])loading settings_module
same module object: True
cached in sys.modules: True
currency: GBPsettings_module.py reads the settings file at its top level, so the read happens when the module is first imported. The second import and the call to importlib.import_module find the module already in sys.modules and return it, so nothing is read again.
A singleton classwhen creation needs control
The instance is created on the first call to instance(), not at import, so a program that never needs it never pays for it. The class is a type, so a test can subclass it or replace _instance with a fake.
A modulewhen one shared namespace is enough
There is no class, access method or _instance, because import settings_module is the access point. The work happens at import time, whether or not it is needed, and replacing the module in a test means patching sys.modules or the names imported from it.
Most Python code that needs one shared object uses a module, and the standard library does too: logging.getLogger("app") returns the same logger object every time, from a registry the logging module keeps. Both forms share the singleton's real weakness: whatever imports the module depends on it without saying so in any signature.
← → move through sections and cards