Question

How can I create nested modules (packages?) with the python c api?

I would like the client code (python) to be able do something like this:

import MainModuleName
import MainModuleName.SubModuleName

Instead of currently:

import MainModuleName
import MainModuleNameSubModuleName

Which imo looks ugly and clutters up the namespace.

Is it possible without having to mess around with file system directories?

Was it helpful?

Solution

You do not "mess around" with file system directories. File system directories are how you create submodules, unless you want to be really obscure and have a lot of needless pain.

You want to have a module called MainModuleName.SubModuleName and then MainModuleName should be a directory with an __init__.py file.

A common way of doing C modules is to put all the C-code in modules with names starting in underscore, in this case _mainmodulename.c, and then importing them from Python files. This is done so that you only need to implement the things in C that has to be in C, and the rest you can do in Python. You can also have pure-Python fallbacks that way. I suggest you do something similar, and create the module structure in Python and then import the classes and functions from C modules with underscore names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top