how.wtf

Singleton in Python

· Thomas Taylor

The Singleton pattern enforces having one instance of a class. This tutorial will showcase how to implement the singleton pattern in Python.

Implementing the Singleton pattern

Using the __new__ dunder method, the creation of the object can be controlled since __new__ is called before the __init__ method.

 1class Singleton:
 2    _instance = None
 3
 4    def __new__(cls):
 5        if cls._instance is None:
 6            cls._instance = super(Singleton, cls).__new__(cls)
 7        return cls._instance
 8
 9s1 = Singleton()
10s2 = Singleton()
11print(s1 == s2) # outputs True

s1 and s2 are the same object in memory.

Why is this beneficial?

The singleton pattern is useful for certain cases:

  1. Logger
  2. Thread Pooling
  3. Caching
  4. Configuration

#python  

Reply to this post by email ↪