Writing a C extension - borrowed references

Tom Evans tevans.uk at googlemail.com
Tue Mar 20 12:22:12 EDT 2018


Hi all

I'm writing my first C extension for Python here, and all is going
well. However, I was reading [1], and the author there is advocating
Py_INCREF 'ing *every* borrowed reference.

Now, I get that if I do something to mutate and perhaps invalidate the
PyObject that was borrowed I can get unpredictable results - eg, by
getting a borrowed reference to a value from a dictionary, clearing
the dictionary and then expecting to use the borrowed reference.

However, if my code does not do things like that, is there a chance of
a borrowed reference being invalidated that is not related to my use
of the thing I borrowed it from? Is this cargo cult advice (sometimes
the gods need this structure, and so to please the gods it must be
everywhere), sensible belt and braces or needless overkill?

Cheers

Tom


[1] http://pythonextensionpatterns.readthedocs.io/en/latest/refcount.html#borrowed-references



More information about the Python-list mailing list