从父文件夹子文件夹中的相对导入模块

编程入门 行业动态 更新时间:2024-10-28 15:35:08
本文介绍了从父文件夹子文件夹中的相对导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样的目录结构

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 ..mon 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 ..mon import foo
from mainmon 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-31 17:22:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/808903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   夹子   模块   夹中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!