Namespace-respecting relative import in Python
I have this folder structure:
package/
__init__.py
misc/
__init__.py
tools.py
subpackage/
__init__.py
submodule.py
I am in submodule.py
, and I would开发者_如何转开发 like to import misc.tools
. I don't want to use absolute import to import package.misc.tools
, because then my package would only work when it's on the PYTHONPATH. So I want to use relative imports. But then, I also want the imported name to be misc.tools
, and not just tools
.
Is it possible?
What about...:
from .. import misc
from ..misc import tools as _
print misc.tools.__file__
This makes misc.tools
available, as the print
confirms, and with the right name and contents.
Inevitably, it also binds the same module to some barename -- I've chosen _
as a typical "throw-away barename", but of course you can del _
right after that, if you wish, and that won't affect misc.tools
.
Also, any other attribute of misc
set in its __init__.py
(or peculiarly in tools.py
) will be available, but then, if the barename misc
itself is available (as it must be if compound name misc.tools
is required), then it's inevitable that it will have all attributes it builds for itself (or that get externally built for it from other code that executes).
精彩评论