In order to find out if a parameter passed to a function is a "temporary" (only passed into the function) or also referenced outside I use Py_REFCNT
. This is done in a C extension package, but for easier reproducibility I decided to provide a Cython implementation based on IPython magic here.
It seems like something changed for functions that accept multiple arguments (it still works as expected for functions that only take one argument) between CPython 3.5 and CPython 3.6:
In [1]: %load_ext cython
In [2]: %%cython
...: cdef extern from "Python.h":
...: Py_ssize_t Py_REFCNT(object o)
...:
...: cpdef func(o, p):
...: return Py_REFCNT(o)
When I run the code on 3.5 it gives me, the expected result:
>>> import numpy as np
>>> func(np.ones(3), np.ones(3))
1
But with 3.6 it gives me 2
:
>>> import numpy as np
>>> func(np.ones(3), np.ones(3))
2
In the comments I was asked about the C code so here it is:
static PyObject *
GetRefCount(PyObject *m, PyObject *args) {
if (PyTuple_CheckExact(args) && PyTuple_Size(args) > 0) {
Py_ssize_t reference_count = Py_REFCNT(PyTuple_GET_ITEM(args, 0));
return PyLong_FromSsize_t(reference_count);
}
PyErr_SetString(PyExc_TypeError, "wrong input");
return NULL;
}
And the method definition:
{"getrefcount", /* ml_name */
(PyCFunction)GetRefCount, /* ml_meth */
METH_VARARGS, /* ml_flags */
"" /* ml_doc */
},
The results are the same:
>>> import numpy as np
>>> getrefcount(np.ones(3)) # 3.5
1
>>> getrefcount(np.ones(3)) # 3.6
2
I would like to know where (and why) the reference count is incremented in 3.6. I have looked through the CPython source code / the Python issue tracker but I couldn't find an answer.
double(n)
function in both versions, which just doesreturn 2 * n
. You're predicting thatn
will have a higher ref count in 3.6, cool. I'm suggesting that 3.6 may have generated additional bytecode operations that take another reference, and release it. Could be within the target (double
) function, or could be at the call site. So diff'ing decompilations would be instructive.func(np.ones(3), np.ones(3))
is identical in 3.5 and 3.6. But thefunc
itself is a built-in (compiled) function and has no bytecode.