How to use PyModule_FromDefAndSpec C API to construct a module?

In PyO3/pyo3#2245 I’m trying to implement PEP 489 - Multi-phase extension module initialization.

We used PyModule_Create C API to create module object for testing and creating submodules before, but PyModule_Create is incompatible with m_slots, the alternative C API I think is PyModule_FromDefAndSpec but there isn’t any example of its usage in the docs: Module Objects — Python 3.10.3 documentation.

So the question is how to use PyModule_FromDefAndSpec C API to construct a module? Mainly I don’t know how to obtain a ModuleSpec object in C (or Rust).

The module spec is typically created by the import machine, e.g. importlib.util.find_spec() returns a ModuleSpec. AFAIK PyModule_FromDefAndSpec does not need a full spec. You should be able to get by with a mocked ModuleSpec that has just a name attribute.

1 Like