简体   繁体   中英

python c api to create a python module

I'm writing a python module in C, and looking for a way to write a module inside of 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 compiling, I'm trying to access the module and its constant via various import methods

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

First two sound reasonable, and work fine. However, the last one doesn't work. I'm expecting that I should have a code that's equivalent to __init__.py script. However, I don't want to write a separate .py file; rather I want to have such code in C init function directly.

For reference, I'm attaching __dict__ and __all__ of both modules.

>>> A.__dict__
{'B': <module 'B' (built-in)>, '__package__': None, '__file__': 'A.so'}
>>> A.B.__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__'
>>> A.B.__all__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__all__'

Thanks,

You haven't actually created an importable module called AB , since A is not a package. You can't create packages in C, only modules; packages are defined by the filesystem (or by an alternate loader, but that would not be pertinent here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM