Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can PyImport_AppendInittab fail?

Tags:

c++

python

c

According to the official docs, PyImport_AppendInittab will return -1 on failure. It does not, however, specify why this function would fail.

I'd like to know if it can only fail due to the programmer's fault (incorrect arguments, not being called at the right time, etc), or if it can also fail because of some other factors that are out of the programmer's control (like Python not being installed).

I'm asking because I want to know if I should handle this with an assert or an exception. Also, in case I should handle it with exceptions, is there any way for me to catch an error message from the Python API that specifies why the function call failed?

like image 583
Paul Manta Avatar asked Oct 22 '25 05:10

Paul Manta


1 Answers

According to the docs, PyImport_AppendInittab() is a convenience wrapper around PyImport_ExtendInittab() and returns -1 "if the table could not be extended". Furthermore, PyImport_ExtendInittab() returns -1 "if insufficient memory could be allocated to extend the internal table". Both functions "should be called before Py_Initialize()".

Consequently, these functions should only fail if the program is out of memory. I guess they could also fail when supplied with invalid arguments, for example when trying to register a built-in module with the same name as an existing one. The latter case is easily avoided, since names of built-in modules are well known.

In summary, you can assume that a return value of -1 means "out of memory", and this should never happen since the function is only called early in the process (before Py_Initialize()), plus the amount of memory required for the module table is rather small.

If PyImport_AppendInittab() fails, Python does not provide an error string. To throw a meaningful exception, you could just report the information you know at this point: failed to add the module MODULENAME to the interpreter's builtin-in modules.

like image 186
Ferdinand Beyer Avatar answered Oct 23 '25 18:10

Ferdinand Beyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!