HOWTO · Python
The Singleton Design Pattern in Python
Learn four Python Singleton approaches, how repeated construction behaves, and when their tradeoffs matter.
On this page
A Singleton limits a class to one shared instance within a defined scope. In Python, you can approximate that behavior with a decorator, a base class, a metaclass, or module state. Each approach changes how construction works, and none automatically provides thread safety or one object shared across separate processes. The examples below show identity checks so you can choose based on how your code uses the class.
How a Singleton Works in Python
Normally, calling a class creates a new object each time. A Singleton changes that construction path so repeated calls return the same object. The guarantee is usually per class and per Python interpreter; it does not mean every program or process sees one global object. The examples use first is second to check whether two names refer to the same object.
Use a Decorator for a Singleton
A decorator can replace a class with a function that caches the first instance. This is compact and keeps the cache close to the decorated class. The tradeoff is that the public name now refers to the wrapper function, not the original class. Class-level operations such as calling a class method through Sample may no longer behave as expected, and tools that inspect the class can see a changed interface.
Run this example:
def singleton(class_):
instances = {}
def get_instance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return get_instance
@singleton
class Sample:
def __init__(self, name="shared"):
self.name = name
first = Sample()
second = Sample("ignored after construction")
print(first is second)
print(second.name)
The supplied runtime check passed. The first call creates the instance; later calls return it, so later constructor arguments do not reinitialize it. The output confirms that both names refer to the same object and that its name remains shared.
Use a Base Class for a Singleton
A base class can centralize instance creation in __new__, which runs before __init__. Store instances by concrete subclass so separate subclasses do not accidentally share one object. Because Python still calls __init__ after __new__ returns, initialization runs on every construction; keep it idempotent or guard initialization if repeating it would overwrite state.
class SingletonBase:
_instances = {}
def __new__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__new__(cls)
return cls._instances[cls]
class Cache(SingletonBase):
def __init__(self):
if not hasattr(self, "values"):
self.values = {}
first = Cache()
second = Cache()
print(first is second)
print(second.values)
The guard prevents a repeated __init__ call from replacing the existing dictionary. Base-class solutions can become difficult to combine with other inheritance behavior, especially when multiple base classes customize object creation. Consider that cost before making Singleton behavior part of a reusable class hierarchy.
Use a Metaclass for a Singleton
A metaclass controls class construction. This Python 3 form keeps the declared class as a class and caches instances separately for each class that uses the metaclass. Its __call__ method runs when the class is called.
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Service(metaclass=SingletonMeta):
def __init__(self, endpoint="local"):
self.endpoint = endpoint
first = Service()
second = Service("another endpoint")
print(first is second)
print(second.endpoint)
This approach preserves class-level operations better than a decorator that returns a function, though a metaclass can conflict with another metaclass required by a base class. The first call’s arguments initialize the cached instance; subsequent calls return it without calling __init__ again. The metaclass=... declaration shown here is Python 3 syntax; the older Python 2 form is not current guidance.
Use a Module as a Singleton
Python caches imported modules in sys.modules within an interpreter. Importing the same module by the same name therefore gives callers the same module object and shared module-level state. This is often the simplest choice when the shared resource is naturally a group of functions and state rather than an instance with a class interface.
import importlib
first = importlib.import_module("__main__")
second = importlib.import_module("__main__")
first.shared_value = "available through the module"
print(first is second)
print(second.shared_value)
This small demonstration imports the running module by its standard name. In an application, put shared state and functions in a dedicated module and have consumers import that module consistently. Module caching is scoped to an interpreter: separate processes have separate module objects, and reloading a module can execute its code again.
Choose an Approach and Understand Its Limits
Use module state when callers need shared functions or configuration, a metaclass when you need construction control while retaining a class, and a decorator when its wrapper interface is acceptable. A base class can make the behavior reusable through inheritance, but it adds initialization and inheritance constraints. If a normal object passed through dependency injection solves the problem, that is often easier to test and reason about.
These examples establish repeated construction behavior only in ordinary single-threaded use. Concurrent first calls can race unless creation is synchronized, and each process or interpreter has its own cache. For resources that must be coordinated across threads, processes, or machines, use an explicit synchronization or shared-service design. Choose a Singleton only when one shared instance within the intended scope is a real requirement.