Skip to content

Instantly share code, notes, and snippets.

@liuqinh2s
Forked from scturtle/gist:3060332
Created January 8, 2017 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuqinh2s/c37080c69a3a72438f0943f1e7306297 to your computer and use it in GitHub Desktop.
Save liuqinh2s/c37080c69a3a72438f0943f1e7306297 to your computer and use it in GitHub Desktop.
python 3 语法变化

Dive Into Python: 2to3

try python 3 online

Six

3 比 2 要慢不少, 囧rz.

基本语法变化

intlong 统一为 int, 表现为 long

真正的除法 1/2 => 0.5, 原语法退化为 1//2

可用 nonlocal 声明非局部变量, 介于 globallocal 之间

去除元组参数解包, 不能再定义 def foo( (a, (b, c)) ):

八进制语法变化: 0755 => 0o755

比较不同时只支持!=, 不再支持<>

比较时若类型不匹配, 抛出 TypeError, 而不是返回 False

raw_input() 更改为 input(), 原input()应用eval(input())

print 变成函数 print()

exec 变成函数 exec()

execfile() 取消, 需用 exec()compile()

apply() 取消, 需用 *** 展开参数

callable() 取消, 应用 hasattr(func, '__call__')

`x` 取消, 需用 repr(x), 避免反引号的嵌套

捕获异常语法的变化:

except ImportError, e 
=> except ImportError as e 
except (RuntimeError, ImportError), e 
=> except (RuntimeError,ImportError) as e 

抛出自定义异常语法变化:

raise MyException, 'msg' 
=> raise MyException('msg')

元祖的列表解析:

[i for i in 1, 2] 
=> [i for i in (1, 2)]

set 可以用大括号来标记了, 但 {} 表示空字典:

set([1, 2, 3]) 
=> {1, 2, 3}

set 的展开式:

set([i for i in a_sequence]) 
=> {i for i in a_sequence}

取消file类, 只能用 open 打开文件, 添加打开文件的 tb 模式, 添加自动关闭文件的 with open(...) as f:语法


字符串的变化

字符串统一为 unicode 的str ,而 bytes 只能存储 0 到 127 的不可修改的整数序列或纯粹的 ASCII 字符, bytesstrdecode(), 反之 encode()

取消 unicode(), 用 str() 即可

使用format()或字符串的同名函数替代 % 格式化

ord(), chr() 可用于 unicode 的 str


迭代器相关的变化

几乎所有返回列表的方法都返回迭代器(或者动态视图)了

字典没有has_key()了, 只能用in运算符, 字典中返回列表的方法现在返回动态视图, 可用作迭代器, 可进行 in 测试

迭代器的函数next()变为__next__(), 增加了全局函数next()

range()的行为现在是xrange()

zip(), map(), filter()不再返回列表而是迭代器, itertoolsizip(), imap(), ifilter() 取消

reduce() 转入 functools 模块里了


类,模块和包方面变化

引入当前目录下的包必须指定相对路径:

from . import mypkg
from .mypkg import subpkg
from .. import fatherpkg

( 扩展的可迭代解包, 新的metaclass语法, class decorator, 增加抽象基类支持 )

httplib, Cookie, cookielib, BaseHTTPServer, SimpleHTTPServer, CGIHttpServer 合并为 http

urllib 和 urllib2 合并为 urllib

cStringIO, StringIO 可直接引入 io, 优先检测c实现

cPickle, pickle 可直接引入 pickle, 优先检测c实现

模块更名列表 from six:

Python 2 name Python 3 name
_builtin_ builtins
ConfigParser configparser
copy_reg copyreg
cPickle pickle
cStringIO.StringIO() io.StringIO
itertools.ifilter() filter()
cookielib http.cookiejar
Cookie http.cookies
htmlentitydefs html.entities
HTMLParser html.parser
httplib http.client
BaseHTTPServer http.server
CGIHTTPServer http.server
SimpleHTTPServer http.server
itertools.imap map
Queue queue
reduce() functools.reduce()
reload() imp.reload()
repr reprlib
SocketServer socketserver
Tkinter tkinter
Dialog tkinter.dialog
FileDialog tkinter.FileDialog
ScrolledText tkinter.scolledtext
SimpleDialog tkinter.simpledialog
Tix tkinter.tix
Tkconstants tkinter.constants
Tkdnd tkinter.dnd
tkColorChooser tkinter.colorchooser
tkCommonDialog tkinter.commondialog
tkFileDialog tkinter.filedialog
tkFont tkinter.font
tkMessageBox tkinter.messagebox
tkSimpleDialog tkinter.simpledialog
robotparser urllib.robotparser
_winreg winreg
xrange() range()
itertools.izip() zip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment