Python:“导入”是什么?更喜欢 - 模块还是包?
假设当前目录中有一个名为 somecode.py
的文件,以及一个名为 somecode
的目录,其中包含一个 __init__.py
文件。现在,我从此目录运行一些其他 Python 脚本,该脚本执行 import somecode
。将导入哪个文件 - somecode.py
或 somecode/__init__.py
?
是否有一个明确且可靠的搜索顺序来解决这个问题?
哦,有人参考过这种行为的官方文档吗? :-)
Suppose in the current directory there is a file named somecode.py
, and a directory named somecode
which contains an __init__.py
file. Now I run some other Python script from this directory which executes import somecode
. Which file will be imported - somecode.py
or somecode/__init__.py
?
Is there even a defined and reliable search order in which this is resolved?
Oh, and does anyone have a reference to official documentation for this behavior? :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
包将在模块之前导入。插图:
foo.py
:foo/__init__.py
:来自交互式解释器:
我不知道这是官方记录的。
按评论编辑:这是在 Mac OS X 10.6.7 上使用 Python 2.7 执行的。我还在 Ubuntu 10.10 上使用 Python 2.6.5 执行了此操作,并得到了相同的结果。
Packages will be imported before modules. Illustrated:
foo.py
:foo/__init__.py
:And from interactive interpreter:
I have no idea where this is officially documented.
Edit per comment: This was performed with Python 2.7 on Mac OS X 10.6.7. I also performed this using Python 2.6.5 on Ubuntu 10.10 and experienced the same result.
使用以下目录在 Windows 10(Python 版本 3.5)和 Ubuntu Linux(Python 版本 2.7 和 3.5)上进行测试:
https://github.com/alphaCTzo7G/stackexchange/tree/master/python/order_import_module_vs_package
结果
模块一直加载,每次都会打印出如下信息:
“you have import foo/init.py"
因此,在这些系统中似乎是一致的,首先加载包。
tested in Windows 10 (Python version 3.5) and on Ubuntu Linux (Python version 2.7 and 3.5) using the following directory:
https://github.com/alphaCTzo7G/stackexchange/tree/master/python/order_import_module_vs_package
Result
The module is always loaded and the following message is printed out every time:
"you have imported foo/init.py"
So it seems to be consistent across these Systems, that the package is loaded first.