Python: Import file in grandparent directory

孤街浪徒 提交于 2019-12-05 08:20:05
package/
    __init__.py
    scripts/
        web/
            __init__.py
            script1.py
        tests/
            __init__.py
            script2.py
    common/
        __init__.py
        utils.py

I've added a bunch of empty __init__.py files to your package. Now you have 2 choices, you can use an absolute import:

 from package.common import utils

or equivalently:

 import package.common.utils as utils

The downside here is that package must somehow be on PYTHONPATH. The other option is to use relative imports:

from ....common import utils

I would generally discourage this approach... It just gets too hard to tell where things are coming from (is that 4 periods or 6?).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!