Commit 3c4e11dd authored by Alex Willmer's avatar Alex Willmer Committed by Stefan Behnel

Describe refcount behaviour of object vs PyObject* (GH-3013)

parent 70def42a
from __future__ import print_function
from cpython.ref cimport PyObject
import sys
python_dict = {"abc": 123}
python_dict_refcount = sys.getrefcount(python_dict)
cdef owned_reference(object obj):
refcount = sys.getrefcount(python_dict)
print('Inside owned_reference: {refcount}'.format(refcount=refcount))
cdef borrowed_reference(PyObject * obj):
refcount = obj.ob_refcnt
print('Inside borrowed_reference: {refcount}'.format(refcount=refcount))
print('Initial refcount: {refcount}'.format(refcount=python_dict_refcount))
owned_reference(python_dict)
borrowed_reference(<PyObject *>python_dict)
......@@ -288,6 +288,17 @@ In the interests of clarity, it is probably a good idea to always be explicit
about object parameters in C functions.
To create a borrowed reference, specify the parameter type as ``PyObject*``.
Cython won't perform automatic ``Py_INCREF``, or ``Py_DECREF``, e.g.:
.. literalinclude:: ../../examples/userguide/language_basics/parameter_refcount.pxd
will display::
Initial refcount: 2
Inside owned_reference: 3
Inside borrowed_reference: 2
.. _optional_arguments:
Optional Arguments
......@@ -579,6 +590,10 @@ Here is an example:
The precedence of ``<...>`` is such that ``<type>a.b.c`` is interpreted as ``<type>(a.b.c)``.
Casting to ``<object>`` creates an owned reference. Cython will automatically
perform a ``Py_INCREF`` and ``Py_DECREF`` operation. Casting to
``<PyObject *>`` creates a borrowed reference, leaving the refcount unchanged.
.. _checked_type_casts:
Checked Type Casts
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment