title: Create default values for dictionary in python
body: <p>Let's have a method that would cache results it calculates.</p>
  
  <p><strong>"If" approach</strong>:</p>
  
  <pre><code>def calculate1(input_values):
      if input_values not in calculate1.cache.keys():
          # do some calculation
          result = input_values
          calculate1.cache[input_values] = result
      return calculate1.cache[input_values]
  calculate1.cache = {}
  </code></pre>
  
  <p><strong>"Except" approach</strong>:</p>
  
  <pre><code>def calculate2(input_values):
      try:
         return calculate2.cache[input_values]
      except AttributeError:
         calculate2.cache = {}
      except KeyError:
         pass
      # do some calculation
      result = input_values
      calculate2.cache[input_values] = result
      return result
  </code></pre>
  
  <p><strong>"get/has" approach</strong>:</p>
  
  <pre><code>def calculate3(input_values):
  
      if not hasattr(calculate3, cache):
          calculate3.cache = {}
  
      result = calculate3.cache.get(input_values)
      if not result:
          # do some calculation
          result = input_values
          calculate3.cache[input_values] = result
      return result
  </code></pre>
  
  <p><strong>Is there another (faster) way? Which one is most <em>pythonic</em>? Which one would you use?</strong></p>
  
  <p><em>Note</em>: There's a speed difference:</p>
  
  <pre><code>calculate = calculateX # depening on test run
  for i in xrange(10000):
      calculate(datetime.utcnow())
  </code></pre>
  
  <p>Results <code>time python test.py</code>:</p>
  
  <pre><code>calculate1: 0m9.579s
  calculate2: 0m0.130s
  calculate3: 0m0.095s
  </code></pre>