[英]Why can't load the module?
Display my project
's directory structure:显示我的
project
的目录结构:
tree project
project
├── config.py
├── __init__.py
└── project.py
Content in project.py: project.py 中的内容:
from . import config
def main():
pass
if __name__ == '__main__':
main()
Content in __init__.py
: __init__.py
中的内容:
__all__ = ['project','config']
from project import *
from . import config
config.py
is blank for simplicity.为简单起见,
config.py
为空白。
To load the module:加载模块:
cd project
import project
It encounter the error info: Parent module '' not loaded, cannot perform relative import
它遇到错误信息:
Parent module '' not loaded, cannot perform relative import
Why can't import project
?为什么不能
import project
? I found that if project.py
renamed as myproject.py
, keep any other thing the same as before, import project
can work.我发现如果
project.py
重命名为myproject.py
,保持其他的和以前一样, import project
就可以了。
Does not the package project
share same name with module project.py
? package
project
是否与模块project.py
共享相同的名称?
Why same names matter?为什么相同的名字很重要?
If you try to look at __package__
from project.py
, you will see that it changes from nothing when you import project
inside the project/
folder, and when you import project
just outside the folder.如果您尝试查看
project.py
中的__package__
,您会发现当您在project/
文件夹内import project
时,以及在文件夹外import project
时,它会从无变化。 This is because, when you are inside the folder, you are importing the module project
(ie the project.py
file), and from outside the project/
folder you are importing the project
package (ie the you are running the __init__.py
file).这是因为,当您在文件夹内时,您正在导入模块
project
(即project.py
文件),而从project/
文件夹外部您正在导入project
package (即您正在运行__init__.py
文件)。
When writing from. import x
写
from. import x
from. import x
, you expect to import x
from inside the current package, but there is no package context, therefore it cannot import.
from. import x
,您希望从当前 package 中导入x
,但没有 package 上下文,因此无法import.
According to this answer: https://stackoverflow.com/a/35710527/4393278根据这个答案: https://stackoverflow.com/a/35710527/4393278
What does
__all__
do?__all__
做什么?
It declares the semantically "public" names from a module.
它从模块中声明语义上的“公共”名称。 If there is a name in all , users are expected to use it, and they can have the expectation that it will not change.
如果all中有一个名字,那么用户就会被期望使用它,并且他们可以期望它不会改变。
` all = ['foo', 'Bar'] means that when you import * from the module, only those names in the all are imported.
` all = ['foo', 'Bar'] 表示当你从模块中导入 * 时,只会导入all中的那些名称。
So you don't need to define __all__
if you want to import anything inside project.py
file.因此,如果要在
project.py
文件中导入任何内容,则无需定义__all__
。 Also I think you should import a file is not by their path.另外我认为您应该导入文件而不是通过它们的路径。 So, inside your
__init__
file, it should be like this.所以,在你的
__init__
文件中,它应该是这样的。
from .project import *
from .config import *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.