2

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?

1 Answer 1

1

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.

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

3 Comments

OK, I will not try to bend python over for my highly aestethic needs :) The underscore scheme seems nice, but does it mean I have to provide python wrappers for all my C functions/classes? Since the users of MainModuleName won't see the _MainModuleName import?
No, you just import the functions from _MainModuleName in MainModuleName.__init__, and users of MainModuleName can import X from MainModuleName.
I see, for some reason I thought that imported names was included when the module is imported into another module. I implemented this approach and I'm very happy with the result. Tack så mycket!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.