title: How to use PyDict_SetDefault with regard to the refence count of default
body: <p>I'm wondering about how to use <a href="https://docs.python.org/3/c-api/dict.html#c.PyDict_SetDefault" rel="nofollow noreferrer"><code>PyDict_SetDefault</code></a> without creating a reference count catastrophe.</p>
  
  <p>The documentation doesn't say anything about a stolen reference and some testing shows that it doesn't "steal the reference" of <code>default</code>. But it increfs it <em>if and only if</em> the key wasn't present in the dictionary.</p>
  
  <p>That seems really complicated to me because it's just too easy to get wrong. I currently use it like this:</p>
  
  <pre class="lang-c prettyprint-override"><code>item = PyDict_SetDefault(dictionary, key, defaultvalue);
  if (item != defaultvalue) {
      /* key was present, the item is a borrowed reference and default is at refcount 1.*/
      Py_INCREF(item);         /* item at refcount 2 */
      Py_DECREF(defaultvalue); /* default at refcount 0 */
      defaultvalue= NULL;
  } else {
      /* key wasn't present, item is default and has refcount 2. */
      defaultvalue = NULL;
  }
  </code></pre>
  
  <p>At the end the dictionary and I own a reference for <code>item</code> and <code>default</code> was cleanly deleted, right?</p>
  
  <p>Is there a better way to deal with the situation without explicitly checking if <code>item == default</code> that I missed? Is it really that complicated or did I miss the <em>obvious and easy</em> way?</p>