PyImport_ImportModule, PyModule_GetDict
Brian Lloyd
Brian at digicool.com
Thu Jul 8 13:34:23 EDT 1999
> If I understand this correctly, the equivalent of doing this:
>
> >>> import mymodule
> >>> dir(mymodule)
>
> is sort of this, in the C API:
>
> PyObject *mod = PyImport_ImportModule("mymodule");
> PyObject *myDict = PyModule_GetDict(mod);
>
> Q: what is the C API equivalent of this:
>
> >>> from mymodule import *
> >>> dir()
>
>
> --Randy
Ok, I'll bite - though I'll note that the 'from module import *'
form is often considered evil :^) Here's an offhand and untested
way you might try to do it:
int fromModuleImportStar(PyObject *modsrc, PyObject *modto) {
PyObject *srcdict=PyModule_GetDict(modsrc);
PyObject *tgtdict=PyModule_GetDict(modtgt);
PyObject *keys=PyDict_Keys(modsrc);
PyObject *key=NULL;
PyObject *val=NULL;
int size=PyList_Size(keys);
int n=0;
while (n < size) {
/* I _think_ that all the references are borrowed here,
so we don't need to INCREF/DECREF...
*/
key=PyList_GetItem(keys, n);
/* should check this for errors */
PyDict_SetItem(tgtdict, key, PyDict_GetItem(srcdict, key));
n++;
}
PY_DECREF(srcdict);
PY_DECREF(tgtdict);
PY_DECREF(keys);
return 0;
}
Hope this helps!
Brian Lloyd brian at digicool.com
Software Engineer 540.371.6909
Digital Creations http://www.digicool.com
More information about the Python-list
mailing list