PYTHON API : add new classes in a module from an other module

M

mathieu gontier

Hi every body

I am tring to create new Python modules.

In a first time, I have created a module named FOO in which I have
inserted new classes. No problem :

PyMODINIT_FUNC initFOO( void )
{
PyObject* module = Py_InitModule3( "FOO", 0, "foo module" ) ;
if ( ! module ) return ;

if ( PyType_Ready( &my_type) < 0 ) return ;
Py_INCREF( &my_type );
PyModule_AddObject( module, "my_pytype", (PyObject*) &my_type ) ;
}

In a second time, I would like create a new module named BAR. In the
'init' function of this module, Ii would like add new classes in FOO.
So, I would like white something like the following :

PyMODINIT_FUNC initBAR( void )
{
foo_module = Py_GetModule( "FOO" ) ;
if( ! foo_module ) return ;

if ( PyType_Ready( &my_addtype) < 0 ) return ;
Py_INCREF( &my_addtype );
PyModule_AddObject( foo_module, "my_pyaddtype", (PyObject*)
&my_addtype ) ;
}

So, my question is : does it exist in the Python API, a equivalent
function of "Py_GetModule( <module name> )" (that a have invented for
the example !) ;
or does an other solution exist in order to do the same think ?

Thanks,
Mathieu
 
A

Alex Martelli

mathieu gontier said:
foo_module = Py_GetModule( "FOO" ) ;
if( ! foo_module ) return ; ...
So, my question is : does it exist in the Python API, a equivalent
function of "Py_GetModule( <module name> )" (that a have invented for
the example !) ;
or does an other solution exist in order to do the same think ?

There is no direct way to "get a module named this way if it is already
imported otherwise do nothing". PyImport_AddModule comes close, but it
will return an empty module (and insert it into sys.modules too...) in
the 'otherwise' case.

PyImport_GetModuleDict returns sys.module to you as a PyObject*
(borrowed reference, so no worry about needing to decref it later), and
then you can call PyDict_GetItemString on it -- the latter DOES return 0
without setting and exception if the string isn't a key in the
dictionary, so overall it may come closest to your desires even though
you do need a two-calls sequence.

Summarizing, then:

{
PyObject* sys_modules = PyImport_GetModuleDict();
PyObject* foo_module = PyDict_GetItemString(sys_modules, "FOO");
if(!foo_module) return;

/* use foo_module freely here, do not decref it when you're done */

}


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top