Expert Python Programming by Michał Jaworski

Expert Python Programming by Michał Jaworski

Author:Michał Jaworski
Language: eng
Format: epub
Tags: COM051360 - COMPUTERS / Programming Languages / Python, COM051240 - COMPUTERS / Software Development and Engineering / Systems Analysis and Design, COM060090 - COMPUTERS / Internet / Application Development
Publisher: Packt Publishing
Published: 2019-04-30T07:21:28+00:00


Note that the preceding signature does not specify the exact list of arguments but only PyObject* args will hold the pointer to the structure that contains the tuple of the provided values. The actual validation of the argument list must be performed inside the function body and this is exactly what fibonacci_py() does. It parses the args argument list assuming it is the single unsigned int type and uses that value as an argument to the fibonacci() function to retrieve the Fibonacci sequence element as shown in the following code:

static PyObject* fibonacci_py(PyObject* self, PyObject* args) { PyObject *result = NULL; long n; if (PyArg_ParseTuple(args, "l", &n)) { result = Py_BuildValue("L", fibonacci((unsigned int)n)); } return result; }

The preceding example function has a serious bug, which the eyes of an experienced developer should spot very easily. Try to find it as an exercise in working with C extensions. For now, we leave it as it is for the sake of brevity. We will try to fix it later when discussing details of dealing with errors in the Exception handling section.

The "l" string in the PyArg_ParseTuple(args, "l", &n) call means that we expect args to contain only a single long value. In case of failure, it will return NULL and store information about the exception in the per thread interpreter state. The details of exception handling will be described a bit later in the Exception handling section.

The actual signature of the parsing function is int PyArg_ParseTuple(PyObject *args, const char *format, ...) and what goes after the format string is a variable length list of arguments that represents parsed value output (as pointers). This is analogous to how the scanf() function from the C standard library works. If our assumption fails and the user provides an incompatible arguments list, then PyArg_ParseTuple() will raise the proper exception. This is a very convenient way to encode function signatures once you get used to it but has a huge downside when compared to plain Python code. Such Python call signatures implicitly defined by the PyArg_ParseTuple() calls cannot be easily inspected inside the Python interpreter. You need to remember this fact when using the code provided as extensions.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.