重组和重命名
标准库
为了一致性和使用起来更容易,Python的标准库在Python 3已经被重组了。所有的模块名现在符合Python代码的风格引导,PEP 8[1];并且一些模块被合并了。
2to3包含的固定器可以处理所有的这些,所以这个章节更多的是引起你是否需要不用2to3转换同时支持Python 2和Python 3的兴趣。
six模块[2]对大多数重组的标准库的整合都有支持。你可以从six.moves导入重组的模块:
>>> from six.moves import cStringIO
在Python 2这等效于:
>>> from cStringIO import StringIO
然而在Python 3这将等效于:
>>> from io import StringIO
如果你想要不用转换并且不想用six模块同时Python 2和Python 3,这也是很容易的。你只需要偿试从一个位置导入,捕捉错误然后从其他位置导入。它和你放Python 3的位置在前或者在后没有关系,都可以同样很好地起作用:
>>> try:
... from io import StringIO
... except ImportError:
... from cStringIO import StringIO
这个表格包含除了另外列出表格的urllib、urllib2 和urlparse重组外的所有标准库的重命名和重组:
Python 2 名字
Python 3 名字
six名字
anydbm
dbm
BaseHTTPServer
http.server
BaseHTTPServer
__builtin__
builtins
builtins
CGIHTTPServer
http.server
CGIHTTPServer
ConfigParser
configparser
configparser
copy_reg
copyreg
copyreg
cPickle
pickle
cPickle
cProfile
profile
cStringIO.StringIO
io.StringIO
cStringIO
Cookie
http.cookies
http_cookies
cookielib
http.cookiejar
http_cookiejar
dbhash
dbm.bsd
dbm
dbm.ndbm
dumbdb
dbm.dumb
Dialog
tkinter.dialog
tkinter_dialog
DocXMLRPCServer
xmlrpc.server
FileDialog
tkinter.FileDialog
tkinter_filedialog
FixTk
tkinter._fix
gdbm
dbm.gnu
htmlentitydefs
html.entities
html_entities
HTMLParser
html.parser
html_parser
httplib
http.client
http_client
markupbase
_markupbase
Queue
queue
queue
repr
reprlib
repr