[英]Python import module vs import _module
While configuring PyDev's Forced Builtins in Aptana I noticed that some modules were referenced by default with an _
(underscore) prefix. 在Aptana中配置PyDev的“ 强制内置”时 ,我注意到默认情况下使用
_
(下划线)前缀引用了某些模块。
So I open a Python interpreter and to my surprise, the imports below work: 因此,我打开了一个Python解释器,令我惊讶的是,下面的导入工作了:
import ast
import _ast
import bisect
import _bisect
import csv
import _csv
# ... and so on
Now if I do a dir()
on the imported modules, I see different contents: 现在,如果我在导入的模块上执行
dir()
,则会看到不同的内容:
>>> dir(csv)
['Dialect', 'DictReader', 'DictWriter', 'Error', ...] # and so on
>>> dir(_csv)
['Dialect', 'Error', ...] # node that DictReader and DictWriter are missing
Finally, help() tells me they are clearly different modules: 最后,help()告诉我它们显然是不同的模块:
>>> help(_csv)
Help on module _csv:
NAME
_csv - CSV parsing and writing.
FILE
/usr/lib64/python2.6/lib-dynload/_csv.so
...
>>> help(csv)
Help on module csv:
NAME
csv - CSV parsing and writing.
FILE
/usr/lib64/python2.6/csv.py
...
So, what's the difference between import module
and import _module
? 那么,
import module
和import _module
什么import _module
? Is there a convention behind it or something like that? 它背后是否有约定?
Some modules use some C code to implement parts that need the speed. 一些模块使用一些 C代码来实现需要速度的部分。 The main module still uses Python glue, and the
_module
version contains the C extension. 主模块仍然使用Python胶水,而
_module
版本包含C扩展名。
See for example the csv.py
module ; 参见例如
csv.py
模块 ; it imports from the _csv.c
C library for most of the functionality, with only the Dialect
, Sniffer
, DictReader
and DictWriter
classes implemented in pure Python. 它从
_csv.c
C库导入了大多数功能,只有在纯Python中实现的Dialect
, Sniffer
, DictReader
和DictWriter
类。
The module
plus _module
convention is just that, a convention. module
加_module
约定就是约定。 Not all C extensions follow this pattern. 并非所有的C扩展都遵循这种模式。
_module
is usually the part of module that is written in C. module
is a python wrapper around it. _module
通常是被写入在C.模块的部分module
被它周围的Python包装。 You shouldn't ever need to import _modules
yourself. 您根本不需要自己导入
_modules
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.