How to create a Singleton class in Python

What is a Singleton class?

A Singleton class is a class of which only one object can be created.

It is not allowed to create more than one object of that class.

This is usually helpful when you some heavy operation, like creating a database connection, in which creating a connection object each time you get a request would not be the right approach. Rather, you can use the same connection object to perform the database operations – this will save computation time as well as computation memory.

How to implement Singleton class

Now, let’s see how to create a Singleton class in Python.

class SingletonClass:
_instance = None
def __new__(cls):
if cls._instance is None:
print('Creating the object')
cls._instance = super(SingletonClass, cls).__new__(cls)
return cls._instance
obj1 = SingletonClass()
print(obj1)
obj2 = SingletonClass()
print(obj2)

Explanation:

  • On line 1, we create our Python class.
  • In line 2, we create an instance variable.
  • In line 4, we override the __new__() method that is called internally by Python when you create an object of a class.
  • In line 5, we check whether our instance variable is None.
  • In line 7, if the instance variable is None, we will create a new object and call the super() method.
  • In line 8, we return the instance variable that contains the object of this class.
  • In lines 10 and 13, we create two objects of our class. But, after we run the code, it becomes clear that the object is only created the first time; after that, the same object instance is returned.

This can also be verified when we print obj1 and obj2, two objects that point to the same memory.

So, in this way, you can create a class and restrict the user to create only one object of that class.

Free Resources