Singleton Design Pattern With Python Sample

What is Singleton Design Pattern?

 
Singleton design pattern is a creational design pattern. It is used to maintain single instance throughout the application.
 

When to use Single Design pattern?

 
When our requirement requires a single instance throughout the application. Then we can take steps to implement this design pattern.
 

Where can we use it?

 
For Database connection, logging, caching purpose etc.
 
Below is the code which defined the Singleton design pattern. The below code is not thread safe.
  1. class singletonSample:  
  2.   
  3.     __instance = None  
  4.  
  5.     @classmethod  
  6.     def getInstance(cls):  
  7.         if not cls.__instance:  
  8.             cls.__instance = singletonSample()  
  9.         return cls.__instance  
Below is the code to access singleton instance.To make sure we have single instance, I am accessing the class with Instance 10 times and matching with some refInstance object, along with printing object reference id i.e. identity of object
  1. from singletonSample import singletonSample  
  2.   
  3. instanceList = []  
  4.   
  5. for index in range(010):  
  6.     instanceList.append(singletonSample.getInstance())  
  7.   
  8. refInstance = singletonSample.getInstance()  
  9.   
  10. print("refInstance object found at: ", id(refInstance))  
  11.   
  12. for instance in instanceList:  
  13.     if instance == refInstance:  
  14.         print("Same object found: ", id(instance))  
  15.     else:  
  16.         print("different object found:", id(instance))  
Below is the output of above code 
 
Singleton Design Pattern With Python Sample
 
If we are using the threads in our application and we are expecting to maintain singleton instance even though the “class.Method” is accessed by threads, in these kind of cases we need thread safe singleton class.
 
Below is the thread safe code.
  1. import threading  
  2.   
  3. class threadSafeSingleton:  
  4.   
  5.     __lockObj = threading.Lock()  
  6.     __instance = None  
  7.     __proposal: str  
  8.  
  9.     @classmethod  
  10.     def getInstance(cls, proposal: str):  
  11.         with cls.__lockObj:  
  12.             if cls.__instance is None:  
  13.                 cls.__proposal = proposal  
  14.                 cls.__instance = threadSafeSingleton()  
  15.         return cls.__instance  
  16.   
  17.     def printProposal(self):  
  18.         print(self.__proposal, "proposed to create instance")  
In thread safe code we can see that we are using instance of threading.Lock() which will be used to lock current class to use for particular thread and unlock it once usage of thread is completed. If multiple threads try to access the instance of class, the first will acquire threading.Lock() and will proceed next, while the rest will wait until the first thread finishes its execution in that class. And again when second thread, third thread so on move one by one synchronously and as first thread already created instance, rest all threads will use same instance for further execution
 
Below is code where we are creating multiple instance in 4 different threads and while creating each instance we are passing thread name. as per above explanation class should maintain the proposal of first thread which is hit to thread safe singleton class,
  1. from threadSafeSingleton import threadSafeSingleton  
  2. import threading  
  3.   
  4.   
  5. def printfun(proposal: str):  
  6.     single = threadSafeSingleton.getInstance(proposal)  
  7.     single.printProposal()  
  8.   
  9.   
  10. threadA = threading.Thread(target=printfun, args=['threadA'])  
  11. threadB = threading.Thread(target=printfun, args=['threadB'])  
  12. threadC = threading.Thread(target=printfun, args=['threadC'])  
  13. threadD = threading.Thread(target=printfun, args=['threadD'])  
  14.   
  15. threadA.start()  
  16. threadB.start()  
  17. threadC.start()  
  18. threadD.start()   
Below is the output of Thread Safe Singleton accessing code. In the below output we can see that threadA hit the Thread Safe Singleton code and created instance and the remaining 3 threads; i.e. thread, threadC, threadD access the same instance created by threadA 
 
Singleton Design Pattern With Python Sample
 

Summary

 
In this article we learned how to create singleton instance and where to use it. And also we saw how to implement thread safe singleton instance.


Similar Articles