title: reference counts in a Python C extension
body: <p>I'm writing my first C extension to Python and am confused about my reference counts.  Here's what I'm trying to do.</p>
  
  <p>I populate a dict in a for loop:</p>
  
  <pre><code>mydict = PyDict_New();
  
  for (...)
  {
      pair = PyTuple_Pack(2, PyString_FromString("some string"),
            PyString_FromString("some other string"));
  
      /* at this point, the refcnt for the tuple is 1, the refcnts for the
         2 string items are 2. Because according to the source, PyString_FromString
         does an INCREF, and PyTuple_Pack() does an INCREF on its items
       */
  
      PyDict_SetItem(mydict, PyString_FromString("some key"), pair);
  
      /* At this point, the key's refcnt is 2.  PyString_FromString sets it to 1 and 
         PyDict_SetItem INCREF's it. Ditto for pair since PyDict_SetItem also INCREF's
         the value.
       */
  
      Py_DECREF(pair);
  
      /* pair's refcnt is 1 which makes sense to me since mydict now owns the tuple, 
         but the refcnt for its items are still at 2.  I don't understand this part.
       */
  }
  
  return mydict;
  </code></pre>
  
  <p>Are my ref counts correct?  In the C API docs, it specifically recommends using <code>PyObject_FromXXX</code>
  functions as arguments to <code>PyTuple_SetItem</code> or <code>PyList_SetItem</code> because they "steal" references.</p>
  
  <p>It's not documented whether <code>PyDict_SetItem</code> steals references.  I'm guessing it doesn't in which case,
  I should do</p>
  
  <pre><code>first = PyString_FromString("some string");
  second = PyString_FromString("some other string");
  pair = PyTuple_Pack(2, first, second);
  Py_DECREF(second);
  Py_DECREF(first);
  </code></pre>
  
  <p>Am I right?</p>