Track Owned and Borrowed C References
Core idea
Ownership is a C API contract, not a property of Python variable names. An owned reference must eventually be released or transferred; a borrowed reference must not be decremented as if owned. Py_NewRef creates an owned reference from a valid object. PyList_GetItem returns a borrowed reference in CPython 3.13; PyList_GetItemRef returns a strong reference. In concurrent contexts a borrowed item may become invalid if its container changes.
items=[{'code':7}]item=items[0]items.clear()print(item['code'])A Python local binding is strong. This is an ownership analogy, not a borrowed C pointer.
Expected output:
7Observe lifetime through a holder
import weakrefclass Item: passitem=Item(); r=weakref.ref(item)container=[item]; del itemprint(r() is container[0])The container maintains lifetime. C code needs its own documented ownership contract.
Expected output:
TrueCommon mistake
Never blindly DECREF a borrowed pointer. Some functions steal references, others do not; inspect each documented success and failure path.
Practice
Review native fixture first_item: mark the borrowed argument, owned result and every NULL path; explain why ownership of the result belongs to the caller.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reference ownership
Check your understanding of reference ownership.
What is printed?
a=[[]]; b=a[0]; a.clear()print(b)What is printed?
a=[1]; b=aprint(a is b)What does Py_NewRef return?
May a borrowed reference be decremented as owned?