[C++-sig] Re: location of initialization matters?

David Abrahams dave at boost-consulting.com
Wed Sep 24 00:49:25 CEST 2003

Martin Blais <blais at iro.umontreal.ca> writes:

> just a follow up on this:  I was able to recreate the scope object for
> my module by import "itself" from the project's init framework, which
> is executed after the Python initMODULE function is called, and since
> at that point the module has had its Py_InitModule() called, I assume
> that doing a PyImport_ImportModuleEx() after that won't have any other
> consequences.  Here is the relevant code::
>     InInit<DlInit::pyextModuleA>::performInitialize()
>     {
>        ... initialize buff here
>        {
>           using namespace python;
>           // Obtain the handle on the already imported module to create a
>           // scope.
>           PyObject* m = ::PyImport_ImportModuleEx( "libDLpyextModuleA",
>                                                    0, 0, 0 );
>           assert( m != 0 );
>           scope module_scope( object( borrowed<PyObject>( m ) ) );
> 	 // Boost.Python declarations using initialized objects here.
>           module_scope.attr( "buff" ) = buff;
>        }
>     }
> This "seems to work" (i.e. it compiles and doesn't crash and I can
> obtain the correct initialized value for the initialized buff).
> I think with this in mind, I could probably leave the initMODULE
> functions empty and always put my Boost.Python declarations in the
> project's performInitialize() methods.
> Do you see any potential problems with this?  

No serious ones, but I've not done an in-depth analysis.  Don't forget
to do C++ -> Python exception handling as neccessary... whatever that
means for your application.

> I'm sure some other projects must have had to do a similar trick.
> I guess my question boils down to:  "can one safely declare new things
> for Python once the module has already been initialized?"  

You can see everything that goes on in the module initialization
function, so it shouldn't be too hard to analyze.

> (i.e. by "declare new things" I mean insert Boost.Python
> declarations, for example, could I declare a new class within a
> function call? (i.e not the initMODULE function))

Surely you realize that:

       >>> import foo
       >>> class X: pass
       >>> foo.X = X

(and such) are legal?

I don't think there are any major problems, as long as you have a
scope(...) set up.

Dave Abrahams
Boost Consulting

More information about the Cplusplus-sig mailing list