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
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.
Pros and Cons
Singleton has almost same pros and cons as that of global state variables.
Pros:
-
They are super handy to use in small projects. But this gain is often momentarily.
Cons:
-
Thread-safety issues
-
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
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:
- Python coding challenges for interviews
- Flask Interview Questions
- Top 100 interview questions on Data Science & Machine Learning
- Python send GMAIL with attachment
- Google Data Scientist interview questions with answers
- Sequence of Differences in Python
- Find extra long factorials in python
Find more on this topic:
Subscribe to Interview Questions
Recommended books for interview preparation:
Similar Posts
- Configure Logging in gunicorn based application in docker container
- Connect to Cassandra with Python 3.x and get Pandas Dataframe
- Connect to MySQL with Python 3.x and get Pandas Dataframe
- Connect to Postgresql with Python 3.x and get Pandas Dataframe
- Python - Get Google Analytics Data
- Installing PySpark with Jupyter notebook on Ubuntu 18.04 LTS
- Python send GMAIL with attachment
- Send rich text multimedia email in Python
- Blueprints in Flask API Development
- Singleton Design Pattern in Python