Singleton Design Pattern in Python

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

Singleton.py
class MySingleton:
   __instance = None
   model = None

   @staticmethod
   def getInstance():
      if MySingleton.__instance == None:
         MySingleton()
      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!")
      else:
         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.

Pros:

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

Cons:

  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

Usage

  • 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. Write a program for Hailstone Sequence in Python

Recommended books for interview preparation:

Find more on this topic: