Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
Ram Rachum Avatar asked Oct 22 '25 03:10

Ram Rachum


1 Answers

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).

like image 86
Alex Martelli Avatar answered Oct 23 '25 18:10

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!