Search code examples
pythonpython-c-api

How to return a tuple containing a None value from the C API?


What is the appropriate way to return a tuple containing a None value from a C extension to Python? I know that a single None value can be created using

result = Py_BuildValue("");

and that a tuple can be created using something like

result = Py_BuildValue("(ii)", 123, 456);

but I do not see a way to combine this to get, for example, a tuple containing a proper integer and a None value.


Solution

  • There's only ever one None object in Python, and you can always refer to it in C as Py_None.

    The code...

    result = Py_BuildValue("");
    

    ...just increments the refcount of Py_None and returns its pointer, so it's the same as...

    Py_INCREF(Py_None);
    result = Py_None;
    

    If you just want to return None, then use...

    Py_INCREF(Py_None);
    return Py_None;
    

    ...or, since Python 2.4, you can do the same thing with a macro...

    Py_RETURN_NONE;
    

    If you return it in a tuple, like this...

    return Py_BuildValue("(O)", Py_None);
    

    ...there's no need to increment the refcount - Py_BuildValue() does that for you.

    But if you return it in a tuple like this...

    PyObject* tuple = PyTuple_New(1);
    Py_INCREF(Py_None);
    PyTuple_SetItem(tuple, 0, Py_None);
    return tuple;
    

    ...then you have to increment the refcount, because PyTuple_SetItem() doesn't do it for you.