title: Restricting creation of object in a singleton class using constructor in python
body: <p>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). </p>
  
  <p>What I mean by this ? Let me explain this with some code snippet. 
  Consider I have one of this below sample :</p>
  
  <pre class="lang-py prettyprint-override"><code>
  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))
  
  </code></pre>
  
  <p>If I run this above code snippet, I would get a result as per below :</p>
  
  <pre class="lang-py prettyprint-override"><code>44824952 - Object created by constructor.
  44826240 - Object created by getInstance() method.
  44826240 - Object created by getInstance() method.
  44826240 - Object created by getInstance() method.
  </code></pre>
  
  <p>One thing to note - if someone calls the constructor after calling <em>getInstance()</em> 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.</p>
  
  <p>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 ?</p>
  
  <p>I found some reference in here - <a href="https://stackoverflow.com/questions/43324267/program-to-restrict-object-creation-in-python">Program to restrict object creation in Python</a>
  but not sure, how we can restrict the first object creation itself. Is there any better way which let's you do that ?</p>
  
  <p>Any thoughts or references ?</p>
  
  <p>Thank you.</p>