title: Python: Dictionary as instance variable
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">&ldquo;Least Astonishment&rdquo; in Python: The Mutable Default Argument</a>  </p>
  </blockquote>
  
  
  
  <p>I'm very confused about the behavior of dictionaries as class instance variables in Python 3.  The way I understand it, instance variables in Python have <em>per-instance</em> storage, unlike class variables which are per-class (similar to what some other languages call "static").</p>
  
  <p>And this seems to hold true, except when the instance variable is a dictionary created from a default parameter.  For example:</p>
  
  <pre><code>class Foo:
      def __init__(self, values = dict()):
          self.values = values
  
  f1 = Foo()
  f1.values["hello"] = "world"
  
  f2 = Foo()
  print(f2.values)
  </code></pre>
  
  <p>This program outputs:</p>
  
  <pre><code>{'hello': 'world'}
  </code></pre>
  
  <p>Huh? Why does the instance <code>f2</code> have the same dictionary instance as <code>f1</code>?</p>
  
  <p>I get the expected behavior if I don't pass in an empty dictionary as a default parameter, and just assign <code>self.values</code> to an empty dictionary explicitly:</p>
  
  <pre><code>class Foo:
      def __init__(self):
          self.values = dict()
  </code></pre>
  
  <p>But I can't see why this should make any difference.</p>