Simple Singleton Object in Python — Non-overridable and otherwise

Shivaji Basu
2 min readOct 1, 2022

Singleton is a handy design pattern. It is a class object that would not have more than one instance at a time. It is useful when you want the states to be held in one place, and be mirrored across modules. This is particularly useful to centrally hold configurations so that all modules stay coordinated.

At the same time, singleton could also be useful in holding temporal data, like sessions. An application restricted to one session at a time could be a singleton to avoid concurrency conflicts.

Here we will show a simple way to implement a singleton with a business example. We will show how a software could schedule,say, a Doctor’s appointment, and ensure that only one consultation session is scheduled at a point in time.

We will use the python class method decorator @classmethod. It is a method qualifier that mirrors the state of an object across all instances of the class. For example, suppose John and David are two siblings of the class twin. If a class method sets John.age as 26, the same would get set for David.age as well.

Similarly, below snippet shows a doctor’s consultation session implemented as a singleton. It ensures only one object of the class Consultation exists at any time.

The trick is, the default __new__ dunder method, which gets invoked during a new object, is intercepted by the class method start_consultation. It ensures the new object inherits the property value of an instance that already existed. It then directs the new instance to the existing one.

Singleton for session control

If the policy requires the singleton session be replaceable by a new one (overridable), the same code applies but with a tweak as shown below.

Overridable singleton sessions

Singleton pattern is important to maintain transaction integrity within complex and changing business rules. Use it wishfully; benefits are rewarding.

--

--