Py_INCREF/DECREF: When

Posted by Izz ad-Din Ruhulessin on Stack Overflow See other posts from Stack Overflow or by Izz ad-Din Ruhulessin
Published on 2011-01-11T12:47:52Z Indexed on 2011/01/11 15:53 UTC
Read the original article Hit count: 267

Filed under:
|

Is one correct in stating the following:

  • If a Python object is created in a C function, but the function doesn't return it, no INCREF is needed, but a DECREF is.

  • [false]If the function does return it, you do need to INCREF, in the function that receives the return value.[/false]

  • When assigning C typed variables as attributes, like double, int etc., to the Python object, no INCREF or DECREF is needed.

  • Assigning Python objects as attributes to your other Python objects goes like this:

          PyObject *foo;
      foo         = bar // A Python object
      tmp                     = self->foo;
      Py_INCREF(foo);
      self->foo   = foo;
      Py_XDECREF(tmp);
//taken from the manual, but it is unclear if this works in every situation

EDIT: --> can I safely use this in every situation? (haven't run into one where it caused me problems)

  • dealloc of a Python object needs to DECREF for every other Python object that it has as an attribute, but not for attributes that are C types.

Edit

With 'C type as an attribute I mean bar and baz:

typedef struct {
    PyObject_HEAD
    PyObject *foo;
    int bar;
    double baz;
} FooBarBaz;

© Stack Overflow or respective owner

Related posts about python

Related posts about python-c-api