__builtins__ and PyImport_AddModule

Mathieu Fenniak laotzu at pobox.com
Mon Mar 15 16:46:31 EST 2004


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 <laotzu at pobox.com>
 PGP Key ID 0xE131EF7B
 http://www.stompstompstomp.com/



More information about the Python-list mailing list