At face value, the C-API function PyModule_New
and PyModule_NewObject
obviously creates a new module object.
The official Python Documentation provides the following explanation for PyModule_NewObject
:
Return a new module object with the name attribute set to name. Only the module’s doc and name attributes are filled in; the caller is responsible for providing a file attribute.
PyModule_New
does the same thing, except it accepts a C string (char*
) as an argument for the module name, instead of a PyObject*
string.
Okay, so this is pretty straightforward, but...
My question is: what is the use of calling the API function PyModule_NewObject
?
Sure, theoretically it would be great for a situation where you want to dynamically create a new module. But the problem is that, in practice, after creating a new module object, the only way to do anything useful to it would be to add objects (like methods, classes, variables, etc.) to the module's __dict__
attribute. This way users of the module could import it and actually do something with it.
The problem is that the __dict__
attribute of a module is read-only:
>>> import re
>>> x = re
>>> re.__dict__ = { "foo" : "bar" }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
So, in practice, there's really no way to do anything useful with a dynamically created module, as far as I can see. So what then, is the purpose of the C API function PyModule_New
?