DEV Community

Mansour Moufid
Mansour Moufid

Posted on

Programmatically create submodules in Python

If you've ever wanted to distribute a Python package as a single file, but keep the benefits of dotted namespaces, here is a tip.

We can generate submodules programmatically and add them to the current module's namespace using importlib.

For example, here is a single file module (named x if you save it to a file named x.py) with a submodule named y:

import importlib.machinery
import importlib.util
import sys

spec = importlib.machinery.ModuleSpec('y', None)
y = importlib.util.module_from_spec(spec)
sys.modules[__name__].y = y

y.abc = 123
Enter fullscreen mode Exit fullscreen mode

In order to do import x.y or from x import y as if x were a package and not simply a module, just add:

sys.modules[__name__ + '.y'] = y
Enter fullscreen mode Exit fullscreen mode

Top comments (0)