How can PyImport_AppendInittab crash?

According to official docs, PyImport_AppendInittab will return -1 on error. However, it does not indicate why this function will fail.

I would like to know if it can fail due to a programmer error (incorrect arguments not called at the right time, etc.), or if it can also fail due to some other factors (e.g. Python doesn't installed).

I ask because I want to know if I should handle this statement or exception. Also, in case I have to handle the exceptions, is there a way to catch an error message from the Python API that indicates why the function call failed?

+2
source share
1 answer

According to the docs, PyImport_AppendInittab() is a convenient wrapper around PyImport_ExtendInittab() and returns -1 "if the table cannot be expanded." In addition, PyImport_ExtendInittab() returns -1 "if insufficient memory can be allocated to expand the internal table. Both functions must be called before Py_Initialize() ".

Therefore, these functions should work only if the program does not work. I think they can also fail if there are invalid arguments, for example, when trying to register a built-in module with the same name as an existing one. In the latter case, it is easy to avoid, since the names of the built-in modules are well known.

In conclusion, you can assume that the return value of -1 means "out of memory", and this should never be, since the function is called only at the beginning of the process (before Py_Initialize() ), plus the amount of memory required for the module table is quite small.

If PyImport_AppendInittab() does not work, Python does not provide an error string. To throw a meaningful exception, you can simply report the information that you know at this moment: it was not possible to add the MODULENAME module to the interpreter's built-in modules.

+5
source

Source: https://habr.com/ru/post/1432306/


All Articles