Singleton with Metaclass

18th May, 2023

Singletons get a bad wrap but they can often be useful when used properly. I came across this pattern for implementing them in Python a couple of years back, it worked well in 2.7 but may be out of date for 3.

class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kw):
if cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args, **kw)
return cls._instance

This can now be implemented in any class you wish to make singleton like so:

class SingleInstance():
__metaclass__ = Singleton
def __init__(self):
def __str__(self):
return 'SingleInstance'