triphook triphook - 3 months ago 26
Python Question

Predefined module aliases in Python?

I'm developing a library of Python modules that is fairly deeply nested, e.g.:

\MyTools
__init__.py
\HydroTools
__init__.py
\bin
\Code
__init__.py
hydro.py
\TerraTools
__init__.py
\bin
\Code
__init__.py
terra.py


Is there some way to define aliases for the modules ahead of time (maybe by modifying init.py?), so that instead of importing with...

from MyTools.HydroTools.Code import hydro
from MyTools.TerraTools.Code import terra


...I could do something cleaner like

from MyTools import hydro, terra

Answer

You want to push these nested packages on top of your module namespace.

In MyTools/__init__.py add:

from .HydroTools.Code import hydro
from .TerraTools.Code import terra