Mastering the Singleton Pattern in Python: Thread‑Safe Implementations
This article explains the purpose of the Singleton pattern, demonstrates multiple Python implementations—including module‑based, decorator, class‑based, __new__ method, and metaclass approaches—covers thread‑safety with locking, and provides complete code examples for each technique.
Singleton Pattern is a common software design pattern that ensures a class has only one instance throughout the system. It is useful when a single shared object, such as a configuration manager, is needed.
In Python there are several ways to implement a singleton:
Using a module
Using a decorator
Using a class
Based on __new__ method
Based on a metaclass
Using a Module
Python modules are naturally singletons because they are loaded only once; the compiled .pyc file is reused on subsequent imports. Defining functions and data in a module therefore provides a singleton object.
class Singleton(object):
def foo(self):
pass
singleton = Singleton()Save the above in mysingleton.py and import singleton wherever needed:
from mysingleton import singletonUsing a Decorator
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x
a1 = A(2)
a2 = A(3)Using a Class
A simple class‑based singleton can be written with a class method that stores the sole instance. However, this version is not thread‑safe.
class Singleton(object):
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instanceWhen multiple threads create the instance simultaneously, different objects may be produced. Adding a lock makes the implementation thread‑safe:
import time, threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instanceRunning ten threads that call Singleton.instance() now prints the same object address for all threads.
Based on __new__ Method
Because object creation first calls __new__, a singleton can be built by overriding this method and protecting it with a lock.
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = object.__new__(cls)
return Singleton._instanceBased on a Metaclass
A metaclass can control instance creation for any class that uses it.
import threading
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self, name):
self.name = nameBoth Foo('name') calls return the same object.
Related knowledge: classes are created by type; creating an object invokes the class’s __new__ and __init__ methods, while calling a class invokes type.__call__.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
