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. """
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.
Pros and Cons
Singleton has almost same pros and cons as that of global state variables.
They are super handy to use in small projects. But this gain is often momentarily.
Singleton makes unit testing very hard
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
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:
- Python coding challenges for interviews
- Flask Interview Questions
- Top 100 interview questions on Data Science & Machine Learning
- Google Data Scientist interview questions with answers
- Python send GMAIL with attachment
- Sequence of Differences in Python
- Write a program for Hailstone Sequence in Python