By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,743 Members | 1,058 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,743 IT Pros & Developers. It's quick & easy.

__builtins__ and PyImport_AddModule

P: n/a
Good day,

I'm writing an application which creates modules and runs Python code on
the fly, embedding Python. The main function of the code is loaded into
the __main__ module: (Error checking omitted for brevity.)

PyObject* module = PyImport_AddModule("__main__");
PyObject* moduleDict = PyModule_GetDict(module);
PyObject* runRetval = PyRun_String(codeStr, Py_file_input,
moduleDict, moduleDict);

I ran into a problem when I tried to do a similar thing with the modules
that 'codeStr' may reference:

PyObject* module = PyImport_AddModule(moduleName);
PyObject* moduleDict = PyModule_GetDict(module);
PyObject* runRetval = PyRun_String(moduleCode, Py_file_input,
moduleDict, moduleDict);

The code in 'moduleCode' was unable to do any imports (__import__ was
not defined), nor use any builtin methods or classes (like Exception).
I dig a bit further into it, and found that __builtins__ was not set in
my new module's dict. This is set for __main__ in initmain() in
pythonrun.c. I ended up having to add the following code to import
__builtin__:

if (PyDict_GetItemString(moduleDict, "__builtins__") == NULL)
{
PyObject* builtinMod = PyImport_ImportModule("__builtin__");
if (builtinMod == NULL ||
PyDict_SetItemString(moduleDict, "__builtins__", builtinMod) != 0)
// blah blah, error handling.
;
Py_XDECREF(builtinMod);
}

Why is __builtins__ not set in a module created by PyImport_AddModule?

--
Mathieu Fenniak <la****@pobox.com>
PGP Key ID 0xE131EF7B
http://www.stompstompstomp.com/
Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.