Python “尝试在非包中进行相对导入”,尽管在一个目录中包含 __init__.py 的包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14664313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Attempted relative import in non-package' although packages with __init__.py in one directory
提问by Alex
I have a module named extended.pywhich contains the following line:
我有一个名为的模块extended.py,其中包含以下行:
from .basic import BasicModule
and the file basic.pyresides in the same directory as does __init__.py. However, when I try to run it as:
并且该文件basic.py与__init__.py. 但是,当我尝试将其运行为:
python extended.py
I get the error:
我收到错误:
ValueError: Attempted relative import in non-package
Also adding the line:
还添加了以下行:
from __future__ import absolute_import
does not solve the problem. Maybe I am too tired to see the obvious - but I don't see the problem here.
不能解决问题。也许我太累了,看不到明显的 - 但我在这里看不到问题。
采纳答案by Martijn Pieters
Relative imports only work for packages, but when you importing in extended.pyyou are running a top-level moduleinstead.
相对导入仅适用于包,但当您导入时,extended.py您正在运行顶级模块。
The current directory may hold a __init__.pyfile but that doesn't make exended.pypart of a package yet.
当前目录可能包含一个__init__.py文件,但它exended.py尚未成为包的一部分。
For something to be considered a package, you need to import the directory nameinstead. The following would work:
对于要被视为包的内容,您需要导入目录名称。以下将起作用:
main.py
packagename\
__init__.py
basic.py
extended.py
then in main.pyput:
然后输入main.py:
import packagename.extended
and only thenis extendedpart of a package and do relative imports work.
只有然后是extended一个包的一部分,做相对导入工作。
The relative import now has something to be relative to, the packagenameparent.
相对进口现在拥有的东西是相对的到的packagename父。

