[英]What does `from six.moves import urllib` do in Python?
I found the following line in Python code:我在 Python 代码中发现了以下行:
from six.moves import urllib
Simultaneously, I can find urllib.py
anywhere.同时,我可以在任何地方找到
urllib.py
。 I found that there is a file six.py
in package root and it has class Module_six_moves_urllib(types.ModuleType):
inside.我发现包根目录下有一个文件
six.py
,里面有class Module_six_moves_urllib(types.ModuleType):
Is this it?是这个吗? How is this defined?
这是如何定义的?
UPDATE更新
Sorry I am new to Python and the question is about Python syntax.抱歉,我是 Python 新手,问题是关于 Python 语法的。 I learned, that what is after
import
is Python file name without a py
extension.我了解到,
import
之后是没有py
扩展名的 Python 文件名。 So, where is this file in this case?那么,在这种情况下,这个文件在哪里?
six is a package that helps in writing code that is compatible with both Python 2 and Python 3. six是一个有助于编写与 Python 2 和 Python 3 兼容的代码的包。
One of the problems developers face when writing code for Python2 and 3 is that the names of several modules from the standard library have changed, even though the functionality remains the same.开发人员在为 Python2 和 3 编写代码时面临的问题之一是标准库中的几个模块的名称发生了变化,尽管功能保持不变。
The six.moves
module provides those modules under a common name for both Python2 and 3 (mostly by providing the Python2 module under the name of the Python 3 module). six.moves
模块以 Python2 和 3 的通用名称提供这些模块(主要是通过在 Python 3 模块的名称下提供 Python2 模块)。
So your line所以你的线
from six.moves import urllib
imports urllib
when run with Python3 and imports a mixture of urllib
, urllib2
and urlparse
with Python2, mimicking the structure of Python3's urllib
.使用 Python3 运行时导入
urllib
并使用 Python2 导入urllib
、 urllib2
和urlparse
的混合,模仿 Python3 的urllib
的结构。 See also here .另见此处。
EDIT to address the update of the question:编辑以解决问题的更新:
TLDR; TLDR; There is not necessarily a direct relation between the imported module
urllib
and a file on the filesystem in this case.在这种情况下,导入的模块
urllib
和文件系统上的文件之间不一定有直接关系。 The relevant file is exactly what six.__file__
points to.相关文件正是
six.__file__
指向的内容。
Third party modules are defined in a file/directory that is listed in sys.path
.第三方模块在
sys.path
中列出的文件/目录中定义。 Most of the time you can find the name of the file a module is imported from by inspecting the __file__
attribute of the module in question, eg six.__file__
.大多数情况下,您可以通过检查相关模块的
__file__
属性找到导入模块的文件名,例如six.__file__
。 However with six.moves
things are not as simple, precisely because the exposed modules might not actually map one to one to actual Python modules but hacked versions of those.然而,对于
six.moves
,事情并不那么简单,正是因为暴露的模块实际上可能不会一对一地映射到实际的 Python 模块,而是这些模块的黑客版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.