Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to create a Singleton class in Python

Harsh Jain

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()

obj2 = SingletonClass()
Create a Singleton class in Python


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



View all Courses

Keep Exploring