Singleton Design Pattern in Python

Carvia Tech | October 29, 2019 | 1 min read | 1 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 Flask Interview Questions
  2. Python coding challenges for interviews
  3. Top 100 interview questions on Data Science & Machine Learning
  4. Google Data Scientist interview questions with answers
  5. Sequence of Differences in Python
  6. Find extra long factorials in python
  7. Send email with attachment 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