TheDiveO
TheDiveO

Reputation: 2681

Python3: How to provide module exports as convenience at the package level?

Hopefully my question won't get me into the Python Hall of Shame.

Anyway, I have a package poo that currently contains only a single module moo. In the future, there might be additional modules inside poo (such as poo.moose). Let's assume that moo is kind of a main-use module and that users want to have all things in moo ready at hand when they import poo, the package. I (and my package users) would like to avoid import poo.moo, import poo.moo as moo, and (gasp!) import poo.*. You know, saving typing is a good thing.

So my idea (which is hopefully not completely off the right way) is to copy the "exports" (functions, variables, classes, ...) of module poo.moo to package poo, in __init.py__. I don't want to overwrite any existing definitions in poo though.

What is a correct, good, proper, and efficient way to achieve this? (Did I use "ideal"? Nah!) Or is that a bad idea at all? Or is this highly spirited Python in the sense of "...and now for something completely different"? ;)

Oh, my packages are Python3 only.

Please note that In python, how do you import all classes from another module without keeping the imported module's namespace? has the answer, but did not understand how this would also apply to the __init__.py code of a Python package. For this reason, my detailed answer below gives such additional details.

Upvotes: 1

Views: 2179

Answers (1)

TheDiveO
TheDiveO

Reputation: 2681

Turns out to be really easy. In the package poo/__init__.py simply do this (absolute) import of the module into the package namespace:

from poo.moo import *

That's it. Now when there's a poo.moo.a() it will become accessible as poo.a() too.

Please note that package definitions aren't overwritten by the (sub) module import, as was my intention: poo.moo.version=42 doesn't overwrite poo.version=13. Exactly what is needed.

I now notice that I'm still addled by those other modularized languages where imports stay private to a module. But in Python all is in plain view, so are package imports in a module/package.

Upvotes: 2

Related Questions