Overview
Python uses reference counting for memory management. Every Python object has a reference count tracking how many references point to it. When the count reaches zero, the object is deallocated.Reference Count Basics
Py_INCREF
PyObject*
required
Object to increment (must not be
NULL)Py_DECREF
PyObject*
required
Object to decrement (must not be
NULL)Py_XINCREF / Py_XDECREF
Py_INCREF/Py_DECREF but safe for NULL pointers.
Example:
Creating References
Py_NewRef
PyObject*
required
Object (must not be
NULL)Py_XNewRef
Py_NewRef but accepts NULL (returns NULL unchanged).
Example:
Safe Reference Management
Py_CLEAR
NULL. Avoids use-after-free bugs.
PyObject*
required
Reference to clear (variable, not just value)
Py_SETREF
src to dst before decrementing old value.
Example:
Py_XSETREF
Py_SETREF but uses Py_XDECREF (safer if dst might be NULL).
Reference Ownership
Borrowed References
Some functions return borrowed references - you don’t own them and shouldn’t decrement. Common borrowed reference functions:PyList_GetItem()- Returns borrowed referencePyTuple_GetItem()- Returns borrowed referencePyDict_GetItem()- Returns borrowed referencePyModule_GetDict()- Returns borrowed reference
Owned References (New References)
Most functions return new references - you own them and must decrement. Common new reference functions:PyLong_FromLong()- Returns new referencePyUnicode_FromString()- Returns new referencePyList_New()- Returns new referencePyObject_GetAttr()- Returns new referencePySequence_GetItem()- Returns new reference (even for lists!)
Stealing References
Some functions steal references - they take ownership without incrementing. Functions that steal:PyList_SetItem()- Steals reference to itemPyTuple_SetItem()- Steals reference to itemPyModule_AddObject()- Steals reference to value
Common Patterns
Function Return Values
Functions should return owned references (new references):None:
Error Handling
Clean up references on error:Structure Members
Manage references in structures:Setter Functions
Implement setters correctly:Debugging Reference Counts
Py_REFCNT
Py_SET_REFCNT
Best Practices
Track OwnershipAlways know whether you own a reference:
Initialize to NULL
Use Helper MacrosPrefer
Py_CLEAR, Py_SETREF, Py_XSETREF over manual reference management:Function Versions
Py_IncRef / Py_DecRef
Py_XINCREF/Py_XDECREF. Used for runtime dynamic embedding.
See Also
Object Protocol
Generic object operations
Memory Allocation
Allocating Python objects
Type Objects
Custom type definitions
Exception Handling
Error handling in C extensions
