Python:什么是“导入"?更喜欢-模块还是包? [英] Python: what does "import" prefer - modules or packages?
问题描述
假设在当前目录中有一个名为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? :-)
推荐答案
包将在模块之前导入.图解:
Packages will be imported before modules. Illustrated:
% tree .
.
|-- foo
| |-- __init__.py
| `-- __init__.pyc
`-- foo.py
foo.py
:
% cat foo.py
print 'you have imported foo.py'
foo/__init__.py
:
% cat foo/__init__.py
print 'you have imported foo/__init__.py'
并通过交互式解释器:
>>> import foo
you have imported foo/__init__.py
我不知道这在哪里正式记录.
I have no idea where this is officially documented.
按评论编辑:这是在Mac OS X 10.6.7上使用Python 2.7执行的.我还在Ubuntu 10.10上使用Python 2.6.5进行了此操作,并得到了相同的结果.
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.
这篇关于Python:什么是“导入"?更喜欢-模块还是包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!