[英]python import ignoring local package
Note that doing this is not a good idea. 请注意,这样做不是一个好主意。 It's confusing, error-prone, and typically completely unnecessary.
它容易混淆,容易出错,而且通常完全没必要。
But for the sake of argument, say you have a local package that with the same name as a global package: 但是为了便于讨论,假设您有一个本地包,该包与全局包同名:
module/
__init__.py
os.py
thisfile.py
inside thisfile.py
, you could explicitly specify that you wanted to import your local version of os.py
using one of the following: 在
thisfile.py
,您可以使用以下方式之一明确指定要导入本地版本的os.py
:
from . import os
from .os import foo
But in fact, with python 2.x, local package resolution is the default. 但是实际上,对于python 2.x,本地包解析是默认设置。 Just a simple
import os
would load the local os.py
instead of the system package. 只需一个简单的
import os
加载本地os.py
而不是系统软件包。
So how do I, inside thisfile.py
import the system-level os
package instead of the locally-defined alternative? 那么,如何在
thisfile.py
导入系统级os
包而不是本地定义的包?
This behaviour is python2 specific. 此行为是特定于python2的。 In python3, imports are absolute by default to fix exactly this kind of problem.
在python3中,导入默认情况下是绝对的,可以完全解决此类问题。
In python2.5+ * , you can fix this behaviour using a future import: 在python2.5 + *中 ,您可以使用以后的导入方式解决此问题:
from __future__ import absolute_import
After that, all imports will be absolute and to import a module which has the same name as a top level module you have to use the explicit relative import syntax. 之后,所有导入都是绝对的,要导入与顶级模块同名的模块,您必须使用显式相对导入语法。
See PEP 328 for further background. 有关更多背景信息,请参见PEP 328 。
* edit: in earlier python versions, the only option would be to modify sys.path
in a way that the top level module is found first - which is actually a terrible solution. *编辑:在较早的python版本中,唯一的选择是以首先找到顶级模块的方式修改
sys.path
这实际上是一个糟糕的解决方案。
You have it the other way around. 反之亦然。
# Absolute import
import os
# Relative import
from . import os
Docs: http://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports 文件: http : //docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports
In older Python (everything below 3.0) versions you have to enable it manually though, here is a list with all the __future__
features 在较旧的Python(一切都在3.0以下)版本中你必须手动启用它,这里是一个包含所有
__future__
功能的列表
For Python 2.5-2.x: 对于Python 2.5-2.x:
from __future__ import absolute_import
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.