Name

PyModule_New

Synopsis

PyObject* PyModule_New(char* name)

Returns a new, empty module object for a module named name. Before the new object is usable, you must add to the object a string attribute named __file__. For example:

PyObject* newmod = PyModule_New("mymodule");
PyModule_AddStringConstant(newmod, "__file_  _",
    "<synthetic>");

After this code is run, module object newmod is ready; you can obtain the module’s dictionary with PyModule_GetDict( newmod ) and pass it directly to such functions as PyRun_String as the globals and possibly also the locals argument.

To run Python code repeatedly, and to discern the diagnosis of syntax errors from that of runtime exceptions raised by the code when it runs, you can compile the Python source to a code object, then keep the code object and run it repeatedly. This is just as true when using the C API as when dynamically executing from Python, as covered in Chapter 13. Two C API functions you can use for this task are the following.

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.