从父文件夹子文件夹中的相对导入模块 [英] Relative importing modules from parent folder subfolder

查看:30
本文介绍了从父文件夹子文件夹中的相对导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样的目录结构

main/
    common/
        foo.py
    A/
        src/
            bar.py

如何使用 Python 的 相对导入bar 导入 foo?通过将其添加到路径中,我得到了一个可行的解决方案,但这很难看.有没有办法在 Python 2.7 中简单地使用单个 import ?

How can I use Python's relative imports to import foo from bar? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single import in Python 2.7?

这是这个问题的更复杂版本:

This is a more complex version of this question:

从父文件夹导入模块

推荐答案

正确的相对导入应该是这样的:

The correct relative import would be this:

from ...common import foo

然而,相对导入只能在一个包中工作.如果 main 是一个包,那么你可以在这里使用相对导入.如果 main 不是包,则不能.

However, relative imports are only meant to work within one package. If main is a package, then you can use relative imports here. If main is not a package, you cannot.

因此,如果您在 /main/ 中运行脚本并执行诸如 import A.src.bar 之类的操作,那么该相对导入将失败并显示Attempted顶级包之外的相对导入".这是因为相对导入试图导入顶级包 A 之外的内容.

Thus, if you're running a script in /main/ and doing something like import A.src.bar, then that relative import will fail with "Attempted relative import beyond toplevel package". This is because the relative import is trying to import something outside of the toplevel package A.

但是,如果您在 / 中运行脚本并执行诸如 import main.A.src.bar 之类的操作,那么相对导入将成功,因为 main 现在是一个包.在这种情况下,以下两个将是等效的:

However, if you're running a script in / and doing something like import main.A.src.bar, then that relative import will succeed because main is now a package. In that case, the following two would be equivalent:

from ...common import foo
from main.common import foo

回答您的评论:. 的含义不会根据脚本的运行位置而改变,它会根据包结构而改变.

To answer your comment: the meaning of the . doesn't change depending on where the script was run from, it changes depending on what the package structure is.

这篇关于从父文件夹子文件夹中的相对导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆