0

According to the accepted answer in Py_INCREF/DECREF: When, Python objects that are created by functions but not explicitly returned should have their reference counts decremented via DECREF. Does this guideline apply to temporary variables? For example, I could use this:

void PythonInterface::SetModule (const char *filename)
{
  PyObject *name = PyUnicode_DecodeFSDefault (filename);
  _module = PyImport_Import (name);
  Py_XDECREF (name);
}

or this:

void PythonInterface::SetModule (const char *filename)
{
  _module = PyImport_Import (PyUnicode_DecodeFSDefault (filename));
}

Are these two bits of code identical, or will the second example cause problems?

porzchop
  • 1
  • 1
  • Temporary variables seem like a perfect example of an object that is created but not returned. I don't see why this would be an exception – DavidW Apr 27 '19 at 07:50
  • This would imply that the second approach should be avoided, since we cannot explicitly decrement temporary variables. What about variable reassignments? Are these to be avoided as well? – porzchop Apr 29 '19 at 19:05
  • Variable reassignments that take place within a function do not alter the issue. Example 1 is still the correct way to manage python reference counts. fyi -- I assume `_module` is declared globally and intended to be kept past the life of `PythonInterface::SetModule` ? – user590028 May 10 '19 at 12:37
  • Re: _module, yes. The idea is that I have a separate GetFunction () to return handles to the desired Python functions. I was hoping to reuse _module through the code; I'd SetModule (file1), then GetFunction (function1), then SetModule (file2), GetFunction (function2), etc. all to the same _module. Should I avoid this? – porzchop May 15 '19 at 19:41

0 Answers0