Supporting Python 3(支持python3)——重組和重命名

重組和重命名

標準庫

爲了一致性和使用起來更容易,Python的標準庫在Python 3已經被重組了。全部的模塊名如今符合Python代碼的風格引導,PEP 8[1];而且一些模塊被合併了。html

2to3包含的固定器能夠處理全部的這些,因此這個章節更多的是引發你是否須要不用2to3轉換同時支持Python 2和Python 3的興趣。python

six模塊[2]對大多數重組的標準庫的整合都有支持。你能夠從six.moves導入重組的模塊:linux

>>> from six.moves import cStringIO

在Python 2這等效於:api

>>> from cStringIO import StringIO

然而在Python 3這將等效於:cookie

>>> from io import StringIO

若是你想要不用轉換而且不想用six模塊同時Python 2和Python 3,這也是很容易的。你只須要償試從一個位置導入,捕捉錯誤而後從其餘位置導入。它和你放Python 3的位置在前或者在後沒有關係,均可以一樣很好地起做用:socket

>>> 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 reprlib
robotparser urllib.robotparser urllib_robotparser
ScrolledText tkinter.scolledtext tkinter_scrolledtext
SimpleDialog tkinter.simpledialog tkinter_simpledialog
SimpleHTTPServer http.server SimpleHTTPServer
SimpleXMLRPCServer xmlrpc.server
StringIO.StringIO io.StringIO
SocketServer socketserver socketserver
test.test_support test.support tkinter
Tkinter tkinter tkinter
Tix tkinter.tix tkinter_tix
Tkconstants tkinter.constants tkinter_constants
tkColorChooser tkinter.colorchooser tkinter_colorchooser
tkCommonDialog tkinter.commondialog tkinter_commondialog
Tkdnd tkinter.dnd tkinter_dnd
tkFileDialog tkinter.filedialog tkinter_tkfiledialog
tkFont tkinter.font tkinter_font
tkMessageBox tkinter.messagebox tkinter_messagebox
tkSimpleDialog tkinter.simpledialog tkinter_tksimpledialog
turtle tkinter.turtle
UserList collections
UserString collections
whichdb dbm
_winreg winreg winreg
xmlrpclib xmlrpc.client

urllib、urllib2和urlparse

urllib、urllib2和urlparse這三個模塊被重組進了urllib.request、urllib.parse和urllib.error這三個新的模塊。由於沒有six的支持,全部你必需要使用前面提到的try/except技巧。ui

Python 2 名字 移動到
urllib._urlopener urllib.request
urllib.ContentTooShortError urllib.error
urllib.FancyURLOpener urllib.request
urllib.pathname2url urllib.request
urllib.quote urllib.parse
urllib.quote_plus urllib.parse
urllib.splitattr urllib.parse
urllib.splithost urllib.parse
urllib.splitnport urllib.parse
urllib.splitpasswd urllib.parse
urllib.splitport urllib.parse
urllib.splitquery urllib.parse
urllib.splittag urllib.parse
urllib.splittype urllib.parse
urllib.splituser urllib.parse
urllib.splitvalue urllib.parse
urllib.unquote urllib.parse
urllib.unquote_plus urllib.parse
urllib.urlcleanup urllib.request
urllib.urlencode urllib.parse
urllib.urlopen urllib.request
urllib.URLOpener urllib.request
urllib.urlretrieve urllib.request
urllib2.AbstractBasicAuthHandler urllib.request
urllib2.AbstractDigestAuthHandler urllib.request
urllib2.BaseHandler urllib.request
urllib2.build_opener urllib.request
urllib2.CacheFTPHandler urllib.request
urllib2.FileHandler urllib.request
urllib2.FTPHandler urllib.request
urllib2.HTTPBasicAuthHandler urllib.request
urllib2.HTTPCookieProcessor urllib.request
urllib2.HTTPDefaultErrorHandler urllib.request
urllib2.HTTPDigestAuthHandler urllib.request
urllib2.HTTPError urllib.request
urllib2.HTTPHandler urllib.request
urllib2.HTTPPasswordMgr urllib.request
urllib2.HTTPPasswordMgrWithDefaultRealm urllib.request
urllib2.HTTPRedirectHandler urllib.request
urllib2.HTTPSHandler urllib.request
urllib2.install_opener urllib.request
urllib2.OpenerDirector urllib.request
urllib2.ProxyBasicAuthHandler urllib.request
urllib2.ProxyDigestAuthHandler urllib.request
urllib2.ProxyHandler urllib.request
urllib2.Request urllib.request
urllib2.UnknownHandler urllib.request
urllib2.URLError urllib.request
urllib2.urlopen urllib.request
urlparse.parse_qs urllib.parse
urlparse.parse_qsl urllib.parse
urlparse.urldefrag urllib.parse
urlparse.urljoin urllib.parse
urlparse.urlparse urllib.parse
urlparse.urlsplit urllib.parse
urlparse.urlunparse urllib.parse
urlparse.urlunsplit urllib.parse

移除的模塊

一些標準庫模塊已經被丟棄。UserDict是一個,但這些類中的一部分有一些差很少的替代品,但不是徹底的兼容。更多信息見取代UserDicturl

大多數其餘被丟棄的模塊都是些已經被替換掉很長久的模塊,或者是一些給支持時期不長的特殊平臺的模塊。這個規則適用並例外的是異常模塊。它包含異常的等級,但全部它們也是內置的,因此你歷來都不須要從異常模塊導入任何東西。所以它已經在Python 3被徹底移除了。spa

除了給Solaris、RIX和Mac OS 9的特殊模塊,在Python 3中被移除模塊列表:

模塊名 註釋
audiodev
Bastion
bsddb185 被bsddb3替代
bsddb3 在CheeseShop可用
Canvas
cfmfile
cl
commands
compiler
dircache
dl 被ctypes替代
exception 見前面
fpformat
htmllib 被html.parser替代
ihooks
imageop
imputil
linuxaudiodev 被ossaudiodev替代
md5 被hashlib替代
mhlib
mimetools 被email替代
MimeWriter 被email替代
mimify 被email替代
multifile 被email替代
mutex
new
popen2 被subprocess替代
posixfile
pure
rexec
rfc822 被email替代
sha 被hashlib替代
sgmllib
sre 被re替代
stat 被os.stat()替代
stringold
sunaudio
sv
test.testall
thread 被threading替代
timing
toaiff
user

被移動的內置函數

有幾個內置函數被移到了標準庫。你能夠用類似的方式來處理他們,經過償試從Python 3的位置導入他們並在失敗時不作任何事:

>>> try:
...     from imp import reload
... except ImportError:
...     pass

被移動的內置函數是:

Python 2 名 Python 3 名 six 名
intern() sys.intern()
reduce() functools.reduce() reduce
reload() imp.reload() reload_module

string模塊調動

有幾個函數存在於string模塊,同時也做爲str類型及實體的方法存在。這些如今已經被從string模塊移除。你還能夠在字符串實體或者從str類型中使用他們。因此在Python 2能夠寫成:

>>> import string
>>> string.upper('Dinsdale!')
'DINSDALE!'

如今須要被寫成下面兩種方式中的一個:

>>> 'Dinsdale!'.upper()
'DINSDALE!'
>>> str.upper('Dinsdale!')
'DINSDALE!'

第一種方式是作這個最多見的一個,可是換成第二個方式能夠作簡單的查找和替換。

被移除的函數是capitalize()、 center()、 count()、expandtabs()、 find()、index()、 join()、ljust()、lower()、lstrip()、maketrans()、 replace()、 rfind()、rindex()、 rjust()、rsplit()、rstrip()、split()、strip()、swapcase()、translate()、upper()及 zfill()。

此外atof()、atoi()和atol()函數被移除,而且被把字符串值變成浮點和整數的構造器取代。由於這些函數從Python 2.0起就廢棄了,也極不像你會實際使用它們的樣子。

函數及方法屬性的重命名

在函數和方法中的不少特殊屬性是在決定Python應該用「雙下劃線」方法來描述被Python使用名前就被命名了。

若是你不使用2ot3處理這個的最簡單方法是要根據Python版本用屬性史定義一個變量並使用getattr來訪問屬性。然而,這個不能在im_class重命名的狀況下的起做用,因此你須要一個函數來取得結果:

>>> import sys
>>> if sys.version_info < (3,):
...     defaults_attr = 'func_defaults'
...     get_method_class = lambda x: x.im_class
... else:
...     defaults_attr = '__defaults__'
...     get_method_class = lambda x: x.__self__.__class__
>>> class Test(object):
...     def hasdefaults(a=1, b=2):
...         pass
>>> method = Test().hasdefaults
>>> getattr(method, defaults_attr)
(1, 2)
>>> get_method_class(method)
<class 'Test'>

Six已經定義了函數來從新獲得最多見的屬性名:

Python 2 名 Python 3 名 six 函數
func_closure __closure__
func_doc __doc__
func_globals __globals__
func_name __name__
func_defaults __defaults__ get_function_defaults()
func_code __code__ get_function_code()
func_dict __dict__
im_func __func__ get_method_function()
im_self __self__ get_method_self()
im_class __self__.__class__

附註:

[1] http://www.python.org/dev/peps/pep-0008/
[2] http://pypi.python.org/pypi/six


本文地址:http://my.oschina.net/soarwilldo/blog/538255

在湖聞樟注:

原文http://python3porting.com/stdlib.html

引導頁Supporting Python 3:(支持Python3):深刻指南

目錄Supporting Python 3(支持Python 3)——目錄

相關文章
相關標籤/搜索