title: Singleton Pattern In Python
body: <p>I am new to Python and I am trying to learn this language by checking and creating examples of design patterns in Python.</p>
  
  <p>I have a confusion with classic implementation of Singleton Pattern. Most of the articles out there mentions following implementation of Singleton as classic</p>
  
  <pre><code>class Singleton(object):
      name = None
  
      @staticmethod
      def instance():
          if '_instance' not in Singleton.__dict__:
              Singleton._instance = Singleton()
  
          return Singleton._instance
  
  
  s1 = Singleton().instance();
  s2 = Singleton().instance();
  
  assert s1 is s2
  </code></pre>
  
  <p>But I am not fully convinced with this implementation because no where we are restricting users from creating multiple objects of Singleton class and I can still create an instance of this class by calling Singleton(). In Java, we prevent this by making constructor of class as Private.</p>
  
  <p>Another implementation someone pointed me out is </p>
  
  <pre><code>class Singleton(object):
      _instances = {}
  
      def __new__(class, *args, **kwargs):
          if class not in class._instances:
              instance = super().__new__(class)
              class.__instances[class] = instance
          return class._instances[class]
  </code></pre>
  
  <p>And this has spinned my head off. Can someone explain me how this works?</p>