Singleton Pattern in Python

Introduction

Consider a practical scenario: we want to track our daily expenses. There are two approaches. The first is to record every expense in the same ledger and settle at the end of the month. The second is to use a new notebook for each expense, resulting in many notebooks at the end of the month that must be consolidated into a final statement. Which approach is better? Most people would agree that the first one is preferable! (Except for the wealthy or the eccentric). Why? Because it saves resources and simplifies management.

In software design patterns, the first approach is known as the Singleton Pattern.

Definition

The Singleton Pattern is a common software design pattern whose primary goal is to ensure that a class has only one instance throughout the application. It becomes useful when exactly one object of a class is needed to control actions across the system.

Ways to Implement the Singleton Pattern in Python

1. Using a Module

In Python, modules are inherently singletons. When a module is first imported, a .pyc file is generated. Subsequent imports load the .pyc file with out re-executing the module code. Therefore, by definning related functions and data in a module, we obtain a singleton object. If a singleton class is desired, it can be implemented as follows:

mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()

Save the above code in a file named mysingleton.py. To use the singleton, import the object from it in other files:

from mysingleton import singleton

2. Using a Decorator

def singleton(cls):
    _instances = {}

    def get_instance(*args, **kwargs):
        if cls not in _instances:
            _instances[cls] = cls(*args, **kwargs)
        return _instances[cls]

    return get_instance


@singleton
class A(object):
    a = 1

    def __init__(self, x=0):
        self.x = x


a1 = A(2)
a2 = A(3)
print(a1 is a2)  # True

3. Implementing via new (Recommended for Convenience)

When instantiating an object, Python first calls the __new__ method (which defaults to object.__new__ if not defined) to create the instance, and then calls the __init__ method to initialize it. By overriding __new__, we can enforce the singleton behavior.

import threading


class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    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._instance


obj1 = Singleton()
obj2 = Singleton()
print(obj1, obj2)


def task(arg):
    obj = Singleton()
    print(obj)


for i in range(10):
    t = threading.Thread(target=task, args=[i])
    t.start()

Output:

<__main__.Singleton object at 0x038B33D0> <__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>

With this approach, instantiation works exactly like a normal class: obj = Singleton(), but only one instance is ever created.

Tags: python Singleton Pattern Design Patterns

Posted on Fri, 09 Oct 2026 16:14:23 +0000 by Jason_London