父文件夹子文件夹中的相对导入模块 [英] Relative importing modules from parent folder subfolder
问题描述
给定这样的目录结构
/main/
/main/common/foo.py
/main/A/
/main/A/src/
/main/A/src/bar.py
如何使用Python的相对导入从 bar <导入
foo
/ code>?通过将其添加到路径中我有一个可行的解决方案,但这很难看。有没有办法简单地在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:
推荐答案
正确的相对导入将是:
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.
因此,如果您在<$中运行脚本c $ c> / main / 并执行类似导入A.src.bar
的操作,然后相对导入将失败并显示尝试相对导入超出toplevel包。这是因为相对导入试图导入顶级包之外的东西 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
.
但是,如果你'在 /
中运行脚本并执行类似导入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屋!