[Pyrex] Borrowed references

Daniele Varrazzo daniele.varrazzo at gmail.com
Sun Jul 30 01:45:34 UTC 2006


On 7/30/06, Eric Huss <e-huss at netmeridian.com> wrote:
> I would recommend writing a wrapper around PyTuple_GetItem that will call
> Py_INCREF.  Optionally, you can just manually call Py_INCREF on the return
> value after every time you call PyTuple_GetItem.

If the borrower function is declared "void *" and its return value
explicitely cast <object>, this is about what pyrexc does for me: the
assignment:

    ii = <object>PyTuple_GET_ITEM(index, i)

gets translated into:

    __pyx_3 = (PyObject *)PyTuple_GET_ITEM(__pyx_v_index,__pyx_v_i);
    Py_INCREF(__pyx_3);

and it is also quite safe: forgetting the explicit cast "<object>"
will make pyrexc to complain "Cannot convert 'void (*)' to Python
object". I would forgot tons of Py_INCREF() if i had to put them by
hand after each borrower call.

> Also, PySequence_GetItem doesn't require this magic, and is pretty fast in
> this situation.

Thank you for the hint (i'm about new in Python C API, so i welcome
any usage advise). Anyway i was trying to figure out an usage pattern
in case of borrowed references: there are many other functions with
the same "signature" (PyErr_Occurred was the first i started with)



More information about the Pyrex mailing list