title: Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works
body: <p>I've been reading <a href="http://www.mindview.net/Books/TIPython" rel="nofollow noreferrer">Thinking in python</a> by Bruce Eckel. Currently, I'm reading the <em>Pattern Concept</em> chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class). </p>
  
  <p>This is my understanding of the code so far: </p>
  
  <ul>
  <li>All <em>Singleton</em> objects are subclasses of <em>Borg</em></li>
  <li><em>_shared_state</em> is initially an empty dictionary</li>
  <li><em>_shared_state</em> is a global variable; Any objects utilizing <em>Borg</em> will have the same <em>_shared_state</em> value</li>
  </ul>
  
  <p>My confusion so far:</p>
  
  <ul>
  <li>What's the purpose of this line: <code>self.__dict__ = self._shared_state</code> ; or the purpose of the dictionary</li>
  <li>How did all the objects of <em>Singletons</em> eventually have the same <em>val</em>, even though they are all different instances of the class. </li>
  <li>In overall, I don't know how <em>Borg</em> works</li>
  </ul>
  
  <p>Many Many thanks in advance!</p>
  
  <p>-Tri</p>
  
  <p>*Update: What is stored in <em>_shared_state</em> after each <em>Singleton</em> object creation?</p>
  
  <pre><code>#: Alex' Martelli's Singleton in Python
  class Borg:
    _shared_state = {}
    def __init__(self):
      self.__dict__ = self._shared_state
  
  class Singleton(Borg):
    def __init__(self, arg):
      Borg.__init__(self)
      self.val = arg
    def __str__(self): return self.val
  
  x = Singleton('sausage')
  print x
  y = Singleton('eggs')
  print y
  z = Singleton('spam')
  print z
  print x
  print y
  print ´x´
  print ´y´
  print ´z´
  output = '''
  sausage
  eggs
  spam
  spam
  spam
  &lt;__main__.Singleton instance at 0079EF2C&gt;
  &lt;__main__.Singleton instance at 0079E10C&gt;
  &lt;__main__.Singleton instance at 00798F9C&gt;
  '''
  </code></pre>