2

I have a project which implements reflection in C++ in order to automatically generate Python bindings. Currently, everything that reflected is added to a single module in Python. However, I'd like to be able to create a Python package, so I can do things like import MyProject.Submodule to avoid polluting a single namespace as I add new types.

However, using the existing embedding/extending guide in Python, I can only create individual modules.

I've been able to do things like this:

// Create the MyProject module
PyObject *m = PyModule_Create(&module);

// Add the submodule to the MyProject module object
PyModule_AddObject(m, "submodule", CreateSubmodule);

But if I do that, import MyProject.submodule won't import my submodule, I have to use import MyProject and then use MyProject.submodule to reference the submodule.

Is there a way to define packages from Python's C API that work consistently with packages defined entirely in Python?

1 Answer 1

3

I managed to figure this out for myself by looking at how os.py handles creating its submodules.

In addition to adding the submodule as an object to the package it lives in, as the code posted in the question does, you also need to add the module to the module dictionary:

PyObject *moduleDict = PyImport_GetModuleDict();
PyDict_SetItemString(moduleDict, "package.submodule", submoduleObject);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.