I am middle of writing a singleton class for one of the requirement in python. I could realize that I am not able to restrict the object creation of that class, if some client makes the call first with constructor before using the singleton class method (means the method which return the only instance of the class).
What I mean by this ? Let me explain this with some code snippet. Consider I have one of this below sample :
import threading
class MyClass:
__instance = None
def __init__(self):
if self.__instance:
raise ValueError("Already exist")
@classmethod
def getInstance(cls):
lock = threading.Lock()
with lock:
if cls.__instance == None:
cls.__instance = MyClass()
return cls.__instance
def printObjInfo(self,obj):
print(id(obj))
if __name__ == '__main__':
ob4 = MyClass()
ob4.printObjInfo(ob4)
obj1 = MyClass.getInstance()
obj1.printObjInfo(obj1)
obj2 = MyClass.getInstance()
obj2.printObjInfo(obj2)
# Create a thread
obj3 = MyClass.getInstance()
obj3.printObjInfo(obj3)
t1 = threading.Thread(target=obj3.printObjInfo, args=(obj3))
If I run this above code snippet, I would get a result as per below :
44824952 - Object created by constructor.
44826240 - Object created by getInstance() method.
44826240 - Object created by getInstance() method.
44826240 - Object created by getInstance() method.
One thing to note - if someone calls the constructor after calling getInstance() method then it's fine we can easily restrict the other object creation. But if it gets called first then we wouldn't be able to control that.
Now the problem is - 1) I can't put any further condition within __init__() to not anyone call this or 2) can't make my constructor private - can I ?
I found some reference in here - Program to restrict object creation in Python but not sure, how we can restrict the first object creation itself. Is there any better way which let's you do that ?
Any thoughts or references ?
Thank you.