超出相对导入中的顶级包错误 [英] beyond top level package error in relative import

查看:4080
本文介绍了超出相对导入中的顶级包错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里似乎已经有一些关于python 3中的相对导入的问题了,但是在经历了很多这些问题后,我仍然找不到我的问题的答案。
所以这是问题所在。

It seems there are already quite some questions here about relative import in python 3, but after going through many of them I still didn't find the answer for my issue. so here is the question.

我有一个如下所示的包裹

I have a package shown below

package/
   __init__.py
   A/
      __init__.py
      foo.py
   test_A/
      __init__.py
      test.py

我在test.py中只有一行:

and I have a single line in test.py:

from ..A import foo

现在,我在文件夹中 package ,我运行

now, I am in the folder of package, and I run

python -m test_A.test

我收到消息

"ValueError: attempted relative import beyond top-level package"

但如果我是在的父文件夹中,例如,我运行:

but if I am in the parent folder of package, e.g., I run:

cd ..
python -m package.test_A.test

一切都很好。

现在我的问题是:当我在的文件夹中时,我在test_A中运行模块子包为 test_A.test ,根据我的理解, ..一个只上升一个级别,这是仍然在文件夹中,为什么它会在顶级包之外提供消息。导致此错误消息的原因是什么?

now my question is: when I am in the folder of package, and I run the module inside the test_A sub-package as test_A.test, based on my understanding, ..A goes up only one level, which is still within the package folder, why it gives message saying beyond top-level package. What is exactly the reason that causes this error message?

推荐答案

为什么不起作用?这是因为python没有记录加载包的位置。因此,当您执行 python -m test_A.test 时,它基本上只会丢弃 test_A.test 实际存储的知识在(即不被视为包)。从..A import foo 尝试试图访问它不再拥有的信息(即加载位置的兄弟目录)。它在概念上类似于在 math 中的文件中允许来自..os导入路径。这将是不好的,因为你希望包是不同的。如果他们需要使用来自另一个包的东西,那么他们应该使用os导入路径中的全局引用它们,并让python在的地方运行$ PATH $ PYTHONPATH

Why doesn't it work? It's because python doesn't record where a package was loaded from. So when you do python -m test_A.test, it basically just discards the knowledge that test_A.test is actually stored in package (i.e. package is not considered a package). Attempting from ..A import foo is trying to access information it doesn't have any more (i.e. sibling directories of a loaded location). It's conceptually similar to allowing from ..os import path in a file in math. This would be bad because you want the packages to be distinct. If they need to use something from another package, then they should refer to them globally with from os import path and let python work out where that is with $PATH and $PYTHONPATH.

当您使用时python -m package.test_A.test ,然后使用来自..A import foo 解析得很好,因为它跟踪了<$ c中的内容$ c> package ,您只是访问已加载位置的子目录。

When you use python -m package.test_A.test, then using from ..A import foo resolves just fine because it kept track of what's in package and you're just accessing a child directory of a loaded location.

为什么python不考虑当前工作目录是一个包吗? NO CLUE ,但是gosh它会很有用。

Why doesn't python consider the current working directory to be a package? NO CLUE, but gosh it would be useful.

这篇关于超出相对导入中的顶级包错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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