开发者

How can PyImport_AppendInittab fail?

开发者 https://www.devze.com 2023-03-23 10:40 出处:网络
According to the official docs, PyImport_AppendInittab will return -1 on failure. It does not, however, specify why this function would fail.

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 be开发者_高级运维cause 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消