Master Python Singleton Patterns: Decorators, Metaclasses, and __new__
This article explains three reliable ways to implement the singleton pattern in Python—using a class decorator, a custom metaclass with __call__, and overriding __new__—including complete code examples and a discussion of common pitfalls.
Using a Class Decorator
A decorator can enforce singleton behavior without the class itself being aware of the restriction. The decorator stores created instances in a dictionary and returns the existing instance on subsequent calls.
def singleton(cls):
instances = {}
def _wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _wrapperApplying this decorator to a class guarantees that only one instance will ever be created.
Metaclass (__metaclass__) and Callable Object (__call__)
In Python, classes are themselves objects created by a metaclass. By defining a custom metaclass that overrides __call__, we can control instance creation and ensure a single shared instance.
class Singleton(type):
def __init__(cls, name, bases, attrs):
super(Singleton, cls).__init__(name, bases, attrs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
# Use super to actually create the instance and avoid recursion
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class Foo(object):
__metaclass__ = SingletonNow every call to Foo() returns the same object, and identity checks confirm the singleton property.
Using __new__
The __new__ method is responsible for creating a new instance before __init__ runs. By overriding it, we can intercept the creation process and store a single instance.
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
passInstances of Foo share the same identity, demonstrating a clean singleton implementation via __new__.
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.
