reference counting and PyTuple_SetItem

Tim Peters tim.one at comcast.net
Thu Jun 10 13:50:20 EDT 2004


[Anne Wilson]
...
>      while (<some condition>)
>      {
> 	pyRHost = PyString_FromString(rHost);

You now own a reference to pyRHost.

> 	Py_INCREF(pyRHost);  /* ---> Note 3 <--- */

Now you own two references to it.

> 	PyTuple_SetItem(pyFiveMinArgs, 4, pyRHost);

Now you own one reference; PyTuple_SetItem stole one.

> 	PyTuple_SetItem(pyOneHourArgs, 4, pyRHost);

Now you own no references.  You must not call Py_DECREF on pyRHost after
this point (unless you obtain a new reference to it first).

Apart from all that, you're cheating in ways that can hurt you:  tuples are
supposed to be immutable objects, and it's not strictly legal to mutate them
inside the loop.  You'd be much better off not trying to micro-optimize
(i.e., build a new tuple each time you need one -- never use PyTuple_SetItem
on the same index twice for a given tuple; the code as-is is too clever to
ever work <0.9 wink>).






More information about the Python-list mailing list