Python: what does “import” prefer - modules or packages?

元气小坏坏 提交于 2019-12-01 13:56:56

问题


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? :-)


回答1:


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'

And from interactive interpreter:

>>> import foo
you have imported foo/__init__.py

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.




回答2:


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.



来源:https://stackoverflow.com/questions/6049825/python-what-does-import-prefer-modules-or-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!