5

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,

1 Answer 1

4

You haven't actually created an importable module called A.B, 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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.