Submodules in dynamic modules?

Steven D. Majewski sdm7g at Virginia.EDU
Thu Jul 26 09:59:47 EDT 2001


On Thu, 26 Jul 2001, Martin Sjgren wrote:

> Is there a standardized way to use submodules in a dynamic module written
> in C? I have a module (foo) that should have a few submodules in it, foo
> by itself won't contain much at all, but it's nice to group things up in
> submodules, so I could do
> 
> from foo import bar
> 
> or
> 
> from foo import bar, baz
> 
> The way I'm doing it right now is that I've more or less copied the source
> code from Py_InitModule4() to set things up, and then insert the module
> object into the dictionary.

I don't know if there's a standard way and I don't know if it's better,
but what I have done is to define the macro:

#define ADD_MODULE(x)     if (-1 == \
    PyModule_AddObject( m, (x), PyImport_ImportModule((x))))  return NULL


And in Carbonmodule.c (for MacOSX) where I have a whole bunch of these
submodules, I have:

   m = Py_InitModule("Carbon",CarbonMethods );

   (void) initWin();
   ADD_MODULE("Win");
   (void) initMenu();
   ADD_MODULE("Menu");
   (void) initEvt();
   ADD_MODULE("Evt");
   (void) initDlg();
   ADD_MODULE("Dlg");

    ... 


This was done because there were problems getting the mac toolbox 
modules to link as separate  shared libs on OSX because of cross
linkages between the modules. 

It was done this way so that, not only would 
"from Carbon import Evt" work, but so that all of the
sub-modules would go into sys.modules, and after an initial
"import Carbon", other imports like "import Evt" unqualified
by the Carbon module would also work, so all previous Mac
"classic" toolbox modules would still work as long as an
"import Carbon" was done sometime before -- possibly in site.py. 


-- Steve Majewski






More information about the Python-list mailing list