Python c api to create python module

I am writing a python module in C and am looking for a way to write a module inside a module.

PyMODINIT_FUNC initA(void) { PyObject* pMod, pSubMod; pMod = Py_InitModule3("A", A_Methods, A_Doc); pSubMod = PyModule_New("B"); PyModule_AddStringConstant(pSubMod, "__doc__", B_Doc); PyModule_AddIntConstant(pSubMod, "SOMETHING", 10); PyModule_AddObject(pMod, "B", pSubMod); ... and so on ... 

After compilation, I try to access the module and its constant using various import methods

 >>> import A >>> print ABSOMETHING 10 >>> from A import B >>> print B.SOMETHING 10 >>> from AB import * Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named B 

The first two sounds are reasonable and work fine. However, the latter does not work. I expect that I should have code equivalent to __init__.py script. However, I do not want to write a separate .py file; rather, I want to have such code in the C init function directly.

For reference, I am attaching __dict__ and __all__ to both modules.

 >>> A.__dict__ {'B': <module 'B' (built-in)>, '__package__': None, '__file__': 'A.so'} >>> AB__dict__ {'SOMETHING': 10, '__package__': None, '__name__': 'B', '__doc__': 'B_Doc'} >>> A.__all__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__all__' >>> AB__all__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__all__' 

Thanks,

+4
source share
1 answer

In fact, you did not create an imported module named AB , since A not a package. You cannot create packages in C, only modules; packages are determined by the file system (or alternative bootloader, but this will not be appropriate here).

+4
source

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


All Articles