Matching relative namespace imports in Python

I have this folder structure:

package/
    __init__.py
    misc/
        __init__.py
        tools.py
    subpackage/
        __init__.py
        submodule.py

I am in submodule.pyand I would like to import misc.tools. I do not want to use absolute imports for imports package.misc.tools, because then my package would only work if it is on PYTHONPATH. Therefore, 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?

+3
source share
1 answer

What about...:

from .. import misc
from ..misc import tools as _

print misc.tools.__file__

This makes misc.toolsavailable, as confirmed print, with the correct name and content.

, barename - _ " barename", , , del _ , , misc.tools.

misc, __init__.py ( tools.py), , barename misc ( , misc.tools), , , ( ).

+5

Source: https://habr.com/ru/post/1721839/


All Articles