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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay