Singleton Design Pattern in Python

Carvia Tech | October 29, 2019 | 1 min read | 139 views | Flask - Python micro web framework

Singleton design pattern belongs to creational design pattern that ensures only one instance is created for the given class.

Singleton provides global point of access to instance created.

How to implement Singleton Pattern in Python

Here we will discuss the implementation for Singleton Design Pattern.
class MySingleton:
   __instance = None
   model = None

   def getInstance():
      if MySingleton.__instance == None:
      return MySingleton.__instance

   def __init__(self):
      if MySingleton.__instance != None:
         """ Raise exception if init is called more than once. """
         raise Exception("This class is a singleton!")
         MySingleton.__instance = self

   def getModel(self):
        if self.model is None:
            self.model = self.loadDeepLearningModel('model_ver1')
        return self.model

   def loadDeepLearningModel(self, model):
        """ Load deep learning model and return. """

Pros and Cons

Singleton has almost same pros and cons as that of global state variables.


  1. They are super handy to use in small projects. But this gain is often momentarily.


  1. Thread-safety issues

  2. Singleton makes unit testing very hard

  3. All the classes that are dependent on the global variables becomes tightly coupled with the singleton instance and changes at one place in code might affect other places elsewhere

  4. They break the modularity of the code


  • Logging is one area where singleton are often useful

  • Loading machine learning and deep learning pre-trained models into Singleton object and then using this singleton while predicting results is quite a famous usecase for Singletons.

Top articles in this category:
  1. Python coding challenges for interviews
  2. Flask Interview Questions
  3. Top 100 interview questions on Data Science & Machine Learning
  4. Google Data Scientist interview questions with answers
  5. Python send GMAIL with attachment
  6. Sequence of Differences in Python
  7. Find extra long factorials in python

Find more on this topic:
Machine Learning image
Machine Learning

Data science, machine learning, python, R, big data, spark, the Jupyter notebook, and much more

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info