PYTHON API : add new classes in a module from an other module
Alex Martelli
aleaxit at yahoo.com
Wed Sep 1 08:35:31 EDT 2004
mathieu gontier <mg.mailing-list at laposte.net> wrote:
...
> 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
More information about the Python-list
mailing list