1

In my efforts to understand how reference count works in python extensions, I built the following module:

#include <Python.h>

PyObject *value;

static PyObject* pyref_store(PyObject *self, PyObject* args) {
  PyArg_ParseTuple(args, "O", &value);
  Py_INCREF(value);
  Py_RETURN_NONE;
}

static PyObject* pyref_load(PyObject *self, PyObject* args) {
  return value;
}

static PyMethodDef PyRefMethods[] = {
  {"store", pyref_store, METH_VARARGS, "Store an object in module ...."},
  {"load", pyref_load, METH_NOARGS, "Load the value store in module ...."},
  {NULL, NULL, 0, NULL}
};

static struct PyModuleDef pyrefmodule = {
  PyModuleDef_HEAD_INIT,
  "pyref",
  NULL,
  -1,
  PyRefMethods
};

PyMODINIT_FUNC PyInit_pyref(void) {
  PyObject *m = PyModule_Create(&pyrefmodule);
  return m;
}

And while trying to test from python REPL with the following steps, The reference count I get is 1.

>>> import sys
>>> import pyref
>>> 
>>> pyref.store("whatever")
>>> sys.getrefcount(pyref.load())
1

Shouldn't the returned reference count be 2 which is the 1 added by my module and the 1 added by getrefcount ? (Python version I'm using is 3.6.9).

bees
  • 11
  • 3

1 Answers1

0

Your pyref_load must also Py_INCREF(value): extension functions must return new references (so that they can return new objects).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76