Since PyImport_CreateModuleFromInitfunc() was added (in 3.15, gh-116146), I ran into some issues from real world use internally at Meta (with 3.15+, as well as our 3.14 fork, which has this backported). Collected here as a single issue for convenience - let me know if splitting is preferred.
The API is built on the internal create_builtin() helper, and inherits a few inittab behaviors that don't make sense for an explicitly-passed init function.
Single-phase submodules get the short name. The package context is never set while initfunc runs, so a single-phase init that creates its module as sub (what pybind11's PYBIND11_MODULE(sub, m) does) ends up with __name__ == 'sub' while the spec says pkg.sub. The original impl handled that, but it was lost somewhere on the way.
Non-ASCII spec names raise UnicodeEncodeError, even for multi-phase modules, which the dynamic loader accepts.
Names registered in PyImport_Inittab are handled silently. Depending on the state of the builtin, initfunc is ignored, or the module created here replaces the builtin for later imports, or (multi-phase builtin) initfunc's module overwrites the real one in sys.modules. sys and builtins fall in the first bucket.
Undocumented semantics. Single-phase modules are added to sys.modules by the call itself, multi-phase ones aren't. The spec name is the module's identity, so a second call with the same name and a different initfunc returns the cached module and never calls the new function.
The existing test only covers one top-level single-phase and one top-level multi-phase module, so none of this was caught.
AI disclosure: I ran into the first issue in production, used Claude Opus 5 and Fable 5.1 to root cause, which flagged the other issues while investigating. Fable 5.1 prepared the fixes.
Demo output before any fix:
pkg.sub: repr=<module 'sub'> __name__=sub
non-ASCII name: UnicodeEncodeError: 'ascii' codec can't encode character '\xf6'
same name, initfunc B after A: which=A calls_a=1 calls_b=0
'_random' via custom initfunc, then `import _random`: <module 'same'> hasattr(Random)=False
Activity
pythongh-157384: Accept non-ASCII names in PyImport_CreateModuleFromI…
pythongh-157384: Refuse inittab names in PyImport_CreateModuleFromIni…
pythongh-157384: Add regression tests for PyImport_CreateModuleFromIn…
pythongh-157384: Set package context in PyImport_CreateModuleFromInit…
pythongh-157384: Document and test PyImport_CreateModuleFromInitfunc(…
itamaro commented on Sep 13, 2026
cc @encukou
All should be backported to 3.15, but not necessarily during the RC, 3.15.1 should be fine.
pythongh-157384: Accept non-ASCII names in PyImport_CreateModuleFromI…
gh-157384: Set package context in PyImport_CreateModuleFromInitfunc() (…
[3.15] gh-157384: Set package context in PyImport_CreateModuleFromIni…
gh-157384: Document and test PyImport_CreateModuleFromInitfunc() sema…
[3.15] gh-157384: Document and test PyImport_CreateModuleFromInitfunc…