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?

monoceres
  • 4,722
  • 4
  • 38
  • 63

1 Answers1

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.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • 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? – monoceres Dec 17 '13 at 07:58
  • No, you just import the functions from `_MainModuleName` in `MainModuleName.__init__`, and users of `MainModuleName` can `import X from MainModuleName`. – Lennart Regebro Dec 17 '13 at 11:05
  • 1
    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! – monoceres Dec 17 '13 at 12:10