Skip to content

Instantly share code, notes, and snippets.

@JeffLabonte
Created September 16, 2019 18:13
Show Gist options
  • Save JeffLabonte/dca0b92427929585ecf4b66640a82127 to your computer and use it in GitHub Desktop.
Save JeffLabonte/dca0b92427929585ecf4b66640a82127 to your computer and use it in GitHub Desktop.

C extension Python - Argument from Python

The C extension can handle only METH_VARARGS which is only tuple and METH_VARARGS | METH_KEYWORDS

Note the third entry (METH_VARARGS). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be METH_VARARGS or METH_VARARGS | METH_KEYWORDS; a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.

When using only METH_VARARGS, the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via PyArg_ParseTuple(); more information on this function is provided below.

The METH_KEYWORDS bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third PyObject * parameter which will be a dictionary of keywords. Use PyArg_ParseTupleAndKeywords() to parse the arguments to such a function.

C Extension Python - Exception handling

In any case, if you want to notify the main loop that you have an exception that needs handling, the C code must return NULL or -1.

If we want to add more details to an exception we need to use PyErr_SetString:

This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not increment its reference count. The second argument is an error message; it is decoded from 'utf-8’.

Similar to PyErr_SetString, there is PyErr_SetObject:

This function is similar to PyErr_SetString() but lets you specify an arbitrary Python object for the “value” of the exception.

If you already have a errno from C, it is possible to you PyErr_SetFromErrno.

This is a convenience function to raise an exception when a C library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is the integer errno value and whose second item is the corresponding error message (gotten from strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return PyErr_SetFromErrno(type); when the system call returns an error.

You can also use PyErr_*, the '*' is the usual Python exception i.e IOError

It is possible to clear an exception with PyErr_Clear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment