Many Instances, One State: The Borg Pattern in Python
This article explains how the Monostate, or Borg, pattern lets many Python instances share one state through the instance dictionary, how it differs from a singleton and a module, and how to avoid its subclass and initializer pitfalls.
Programs often need state that every part of the code sees identically, such as configuration values or a registry of handlers, and the usual answer, the Singleton pattern, ensures that only one instance of a class can ever exist. The present article examines an alternative that is particularly natural in Python, the Monostate pattern, better known in the Python community as Borg: any number of instances may be created, but all of them share one state. It explains how the idiom works through the instance dictionary, distinguishes identity from shared state, reproduces the errors that the classic recipe causes in subclasses and initializers, and compares the pattern with a singleton and with the simplest option of all, a module. Letting every instance be created normally while all of them read and write the same attributes is the secret weapon of this pattern.
"Resistance Is Futile": Every Instance Joins One State
The idiom was published by Alex Martelli, first as an ActiveState recipe and then, in 2002, in the Python Cookbook, under a title that rejected the Singleton altogether; the name Borg, suggested by the editor of the Cookbook, refers to the collective of the Star Trek universe, whose members share a single mind. The mechanism relies on the fact that the attributes of an ordinary instance live in its __dict__, and that this dictionary can be replaced: if every instance assigns the same class-level dictionary to its __dict__, an attribute written through one instance is immediately visible through all of them.
class Settings:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
self.__dict__.setdefault("theme", "light")
first, second = Settings(), Settings()
first.theme = "dark"
second.language = "es"
print(second.theme, first.language) # Output: dark es
print(first is second, first.__dict__ is second.__dict__) # Output: False True
print(vars(Settings())) # Output: {'theme': 'dark', 'language': 'es'}
The two objects are distinct, as is shows, yet they share every attribute, and a third instance created later sees both values at once. The default value is set with setdefault, so creating a new instance never overwrites a value that another part of the program has already changed.
Monostate, Singleton and Modules
Consequently, the difference from a singleton lies in what is unique: a singleton guarantees a single object, usually by intercepting the call to the class, for example through the __call__ method of a metaclass, as described in the article devoted to metaclasses; a monostate allows many objects and guarantees a single state. Client code cannot tell the two apart as long as it only reads and writes attributes, but identity checks, sets and dictionaries keyed by the object behave differently, since every monostate instance is a separate object. Both are frequently unnecessary in Python, because a module is created once and cached in sys.modules, so a configuration module whose attributes are read and assigned by every importer already provides one shared state, without any class.
Pitfalls of the Monostate Pattern
A monostate hides global state behind ordinary instance syntax, so its errors are those of global state, made harder to see. Six pitfalls are distinguished, which are the following:
- Subclasses that share the base dictionary. With the recipe as written, every subclass uses the dictionary of the base class, so unrelated subclasses read and overwrite one another's attributes.
- Initializers that reset the state. An assignment in
__init__runs on every instantiation, so creating a new instance silently restores the default and discards the changes made elsewhere. - Classes without
__dict__. A class that declares__slots__, as described in the article devoted to__slots__, has no instance dictionary to replace, and the assignment raisesAttributeError. - Hidden coupling. Code that creates an instance appears to receive a fresh object, while in fact it depends on everything that the rest of the program has written.
- Tests that leak state. One test that changes the shared state affects every test that runs after it, unless the dictionary is cleared between tests.
- Threads. Compound updates of the shared dictionary, such as reading a counter and writing it back, need a lock like any other shared data.
The first two pitfalls are reproduced in the following example, together with a base class that gives each subclass a dictionary of its own through __init_subclass__, the hook described in the article devoted to __init_subclass__.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Cache(Borg):
pass
class Config(Borg):
pass
Cache().entries = 3
print(Config().entries) # Output: 3
class Counter:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
self.count = 0
counter = Counter()
counter.count += 5
Counter()
print(counter.count) # Output: 0
class IsolatedBorg:
_shared_state = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls._shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class SafeCache(IsolatedBorg):
pass
class SafeConfig(IsolatedBorg):
pass
SafeCache().entries = 3
print(hasattr(SafeConfig(), "entries")) # Output: False
The configuration object reports three cache entries because both subclasses inherited the same dictionary, and the counter returns to zero because the second instantiation ran self.count = 0 again. In the isolated version, each subclass receives a new dictionary when it is defined, so instances of one class share their state with one another and with no other class.
Choosing How to Share State
The decision depends on whether identity matters and on whether a class is needed at all, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Shared configuration read by many modules | A module with plain attributes |
| Exactly one object whose identity matters | A singleton, for example through a metaclass or a module-level instance |
| Many instances that must see one state | A monostate with defaults set by setdefault |
| Several monostate classes in one hierarchy | A dictionary per subclass, assigned in __init_subclass__ |
| State that tests must control | An explicit object passed to the code that needs it |
| Shared state modified by several threads | Any of the above, protected by a lock |
Conclusion
It is concluded that the Monostate pattern, which Python programmers call Borg, shares one state among any number of instances by giving all of them the same instance dictionary, and that it differs from a singleton by making the state unique rather than the object. This magic depends on initializing defaults without overwriting shared values, on giving each subclass its own dictionary and on remembering that a module already offers shared state without any class. Controlling the creation of the instance itself, before __init__ runs, which is how singletons and immutable types are built, is the purpose of the special method __new__, which is developed in a future article of this series.