2to3print statementhas_key() dictionary methodfilter() global functionmap() global functionreduce() global function (3.1+)apply() global functionintern() global functionexec statementexecfile statement (3.1+)repr literals (backticks)try...except statementraise statementthrow statementlong data typexrange() global functionraw_input() and input() global functionsfunc_* function attributesxreadlines() I/O methodlambda functions with multiple parametersnext() iterator method__nonzero__ special class attributesys.maxintunicode() global functioncallable() global functionzip() global functionStandardError() exceptiontypes module constantsisinstance global function (3.1+)basestring datatypeitertools modulesys.exc_type, sys.exc_value, sys.exc_tracebackos.getcwdu() functionset() literalsbuffer() global functionFIXME intro
...
print statementIn Python 2, print was a statement -- whatever you wanted to print simply followed the print keyword. In Python 3, print() is a function -- whatever you want to print is passed to print() like any other function.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | print |
print() |
| ② | print 1 |
print(1) |
| ③ | print 1, 2 |
print(1, 2) |
| ④ | print 1, 2, |
print(1, 2, end=' ') |
| ⑤ | print >>sys.stderr, 1, 2, 3 |
print(1, 2, 3, file=sys.stderr) |
print() without any arguments.print() with one argumentprint() with two arguments.print statement with a comma, it would print the values separated by spaces, then print a trailing space, then stop without printing a carriage return. In Python 3, the way to do this is to pass end=' ' as a keyword argument to the print() function. The end argument defaults to '\n' (a carriage return), so overriding it will suppress the carriage return after printing the other arguments.sys.stderr -- by using the >>pipe_name syntax. In Python 3, the way to do this is to pass the pipe in the file keyword argument. The file argument defaults to sys.stdout (standard out), so overriding it will output to a different pipe instead.Python 2 supported <> as a synonym for !=, the not-equals comparison operator. Python 3 supports the != operator, but not <>.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | if x <> y: |
if x != y: |
| ② | if x <> y <> z: |
if x != y != z: |
has_key() dictionary methodIn Python 2, dictionaries had a has_key() method to test whether the dictionary had a certain key. In Python 3, this method no longer exists. Instead, you need to use the in operator.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | a_dictionary.has_key("PapayaWhip") |
"PapayaWhip" in a_dictionary |
| ② | a_dictionary.has_key(x) or a_dictionary.has_key(y) |
x in a_dictionary or y in a_dictionary |
| ③ | a_dictionary.has_key(x or y) |
(x or y) in a_dictionary |
| ④ | a_dictionary.has_key(x + y) |
(x + y) in a_dictionary |
| ⑤ | x + a_dictionary.has_key(y) |
x + (y in a_dictionary) |
or operator takes precedence over the in operator, so there is no need for parentheses here.or takes precedence over in.in operator takes precedence over the + operator, so this form needs parentheses too.In Python 2, many dictionary methods returned lists. The most frequently used methods were keys(), items(), and values(). In Python 3, all of these methods return dynamic views. In some contexts, this is not a problem. If the method's return value is immediately passed to another function that iterates through the entire sequence, it makes no difference whether the actual type is a list or a view. In other contexts, it matters a great deal. If you were expecting a complete list with individually addressable elements, your code will choke, because views do not support indexing.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | a_dictionary.keys() |
list(a_dictionary.keys()) |
| ② | a_dictionary.items() |
list(a_dictionary.items()) |
| ③ | a_dictionary.iterkeys() |
iter(a_dictionary.keys()) |
| ④ | [i for i in a_dictionary.iterkeys()] |
[i for i in a_dictionary.keys()] |
| ⑤ | min(a_dictionary.keys()) |
no change |
2to3 errs on the side of safety, converting the return value from keys() to a static list with the list() function. This will always work, but it will be less efficient than using a view. You should examine the converted code to see if a list is absolutely necessary, or if a view would do.items() method. 2to3 will do the same thing with the values() method.iterkeys() method anymore. Use keys(), and if necessary, convert the view to an iterator with the iter() function.2to3 recognizes when the iterkeys() method is used inside a list comprehension, and converts it to the keys() method (without wrapping it in an extra call to iter()). This works because views are iterable.2to3 recognizes that the keys() method is immediately passed to a function which iterates through an entire sequence, so there is no need to convert the return value to a list first. The min() function will happily iterate through the view instead. This applies to min(), max(), sum(), list(), tuple(), set(), sorted(), any(), and all().Several modules in the Python Standard Library have been renamed. Several other modules which are related to each other have been combined or reorganized to make their association more logical.
FIXME: once the rest of the book is written, these should link back to the chapters and sections that explain these modules.
http packageIn Python 3, several related HTTP modules have been combined into a single package, http.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | import httplib |
import http.client |
| ② | import Cookie |
import http.cookies |
| ③ | import cookielib |
import http.cookiejar |
| ④ | |
import http.server |
http.client module implements a low-level library that can request HTTP resources and interpret HTTP responses.http.cookies module provides a Pythonic interface to "cookies" that are sent in a Set-Cookie: HTTP header.http.cookiejar module manipulates the actual files on disk that popular web browsers use to store cookies.http.server module provides a basic HTTP server.urllib packagePython 2 had a rat's nest of overlapping modules to parse, encode, and fetch URLs. In Python 3, these have all been refactored and combined in a single package, urllib.
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | import urllib |
import urllib.request, urllib.parse, urllib.error |
| ② | import urllib2 |
import urllib.request, urllib.error |
| ③ | import urlparse |
import urllib.parse |
| ④ | import robotparser |
import urllib.robotparser |
| ⑤ | |
|
| ⑥ | |
|
urllib module in Python 2 had a variety of functions, including urlopen() for fetching data and splittype(), splithost(), and splituser() for splitting a URL into its constituent parts. These functions have been reorganized more logically within the new urllib package. 2to3 will also change all calls to these functions so they use the new naming scheme.urllib2 module in Python 2 has been folded into into the urllib package in Python 3. All your urllib2 favorites -- the build_opener() method, Request objects, and HTTPBasicAuthHandler and friends -- are still available.urllib.parse module in Python 3 contains all the parsing functions from the old urlparse module in Python 2.urllib.robotparser module parses robots.txt files.FancyURLopener class, which handles HTTP redirects and other status codes, is still available in the new urllib.request module. The urlencode function has moved to urllib.parse.Request object is still available in urllib.request, but constants like HTTPError have been moved to urllib.error.dbm packageAll the various DBM clones are now in a single package, dbm. If you need a specific variant like GNU DBM, you can import the appropriate module within the dbm package.
| Notes | Python 2 | Python 3 |
|---|---|---|
import dbm |
import dbm.ndbm |
|
import gdbm |
import dbm.gnu |
|
import dbhash |
import dbm.bsd |
|
import dumbdbm |
import dbm.dumb |
|
|
import dbm |
xmlrpc packageXML-RPC is a lightweight method of performing remote RPC calls over HTTP. The XML-RPC client library and several XML-RPC server implementations are now combined in a single package, xmlrpc.
| Notes | Python 2 | Python 3 |
|---|---|---|
import xmlrpclib |
import xmlrpc.client |
|
|
import xmlrpc.server |
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | |
import io |
| ② | |
import pickle |
| ③ | import __builtin__ |
import builtins |
| ④ | import copy_reg |
import copyreg |
| ⑤ | import Queue |
import queue |
| ⑥ | import SocketServer |
import socketserver |
| ⑦ | import ConfigParser |
import configparser |
| ⑧ | import repr |
import reprlib |
| ⑨ | import commands |
import subprocess |
cStringIO as StringIO, and if that failed, to import StringIO instead. Do not do this in Python 3; the io module does it for you. It will find the fastest implementation available and use it automatically.pickle module does it for you.builtins module contains the "global" functions, classes, and constants used throughout the Python language. Redefining a function in the builtins module will redefine the "global" function everywhere. That is exactly as powerful and scary as it sounds.copyreg module adds pickle support for custom types defined in C.queue module implements a multi-producer, multi-consumer queue.socketserver module provides generic base classes for implementing different kinds of socket servers.configparser module parses INI-style configuration files.reprlib module reimplements the built-in repr() function, but with limits on how many values are represented.subprocess module allows you to spawn processes, connect to their pipes, and obtain their return codes.FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | FIXME |
FIXME |
filter() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | filter(a_function, a_sequence) |
list(filter(a_function, a_sequence)) |
| ② | list(filter(a_function, a_sequence)) |
no change |
| ③ | filter(None, a_sequence) |
[i for i in a_sequence if i] |
| ④ | for i in filter(None, a_sequence) |
no change |
| ⑤ | [i for i in filter(a_function, a_sequence)] |
no change |
map() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | map(a_function, 'PapayaWhip') |
list(map(a_function, 'PapayaWhip')) |
| ② | map(None, 'PapayaWhip') |
list('PapayaWhip') |
| ③ | map(lambda x: x+1, range(42)) |
[x+1 for x in range(42)] |
| ④ | for i in map(a_function, a_sequence): |
unchanged |
| ⑤ | [i for i in map(a_function, a_sequence)] |
unchanged |
reduce() global function (3.1+)FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | reduce(a, b, c) |
|
apply() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | apply(a_function, args) |
a_function(*args) |
| ② | apply(a_function, args, kwds) |
a_function(*args, **kwds) |
| ③ | apply(a_function, args + z) |
a_function(*args + z) |
| ④ | apply(aModule.a_function, args) |
aModule.a_function(*args) |
intern() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | intern(aString) |
sys.intern(aString) |
exec statementFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | exec codeString |
exec(codeString) |
| ② | exec codeString in a_global_namespace |
exec(codeString, a_global_namespace) |
| ③ | exec codeString in a_global_namespace, a_local_namespace |
exec(codeString, a_global_namespace, a_local_namespace) |
execfile statement (3.1+)FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | execfile("a_filename") |
execfile(compile(open("a_filename").read(), "a_filename", "exec")) |
repr literals (backticks)FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | `x` |
repr(x) |
| ② | `1 + 2` |
repr(1 + 2) |
| ③ | `"PapayaWhip" + `2`` |
repr("PapayaWhip" + repr(2)) |
try...except statementFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | |
|
| ② | |
|
| ③ | |
unchanged |
| ④ | |
unchanged |
raise statementFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | raise MyException, "error message" |
raise MyException("error message") |
| ② | raise MyException, "error message", a_traceback |
raise MyException("error message").with_traceback(a_traceback) |
| ③ | raise "error message" |
unsupported |
throw statementFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | aGenerator.throw(MyException) |
unchanged |
| ② | aGenerator.throw(MyException, "error message") |
aGenerator.throw(MyException("error message")) |
| ③ | aGenerator.throw("error message") |
unsupported |
long data typeFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | x = 1000000000000L |
x = 1000000000000 |
| ② | x = 0xFFFFFFFFFFFFL |
x = 0xFFFFFFFFFFFF |
| ③ | long(x) |
int(x) |
| ④ | type(x) is long |
type(x) is int |
| ⑤ | isinstance(x, long) |
isinstance(x, int) |
xrange() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | xrange(10) |
range(10) |
| ② | a_sequence = range(10) |
a_sequence = list(range(10)) |
| ③ | [i for i in xrange(10)] |
[i for i in range(10)] |
| ④ | for i in range(10): |
unchanged |
| ⑤ | sum(range(10)) |
unchanged |
raw_input() and input() global functionsFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | raw_input() |
input() |
| ② | raw_input("prompt") |
input("prompt") |
| ③ | input() |
eval(input()) |
| ④ | input("prompt") |
eval(input("prompt")) |
func_* function attributesFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | a_function.func_closure |
a_function.__closure__ |
| ② | a_function.func_doc |
a_function.__doc__ |
| ③ | a_function.func_name |
a_function.__name__ |
| ④ | a_function.func_defaults |
a_function.__defaults__ |
| ⑤ | a_function.func_code |
a_function.__code__ |
| ⑥ | a_function.func_globals |
a_function.__globals__ |
| ⑦ | a_function.func_dict |
a_function.__dict__ |
xreadlines() I/O methodFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | for line in a_file.xreadlines(): |
for line in a_file: |
| ② | for line in a_file.xreadlines(5): |
unchanged |
lambda functions with multiple parametersFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | lambda (x,): x + f(x) |
lambda x1: x1[0] + f(x1[1]) |
| ② | lambda (x, y): x + f(y) |
lambda x_y: x_y[0] + f(x_y[1]) |
| ③ | lambda (x, (y, z)): x + y + z |
lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1] |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | aClassInstance.aClassMethod.im_func |
aClassInstance.aClassMethod.__func__ |
| ② | aClassInstance.aClassMethod.im_self |
aClassInstance.aClassMethod.__self__ |
| ③ | aClassInstance.aClassMethod.im_class |
aClassInstance.aClassMethod.self.__class__ |
next() iterator methodFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | anIterator.next() |
next(anIterator) |
| ② | a_function_that_returns_an_iterator().next() |
next(a_function_that_returns_an_iterator()) |
| ③ | |
|
| ④ | |
unchanged |
| ⑤ | |
|
__nonzero__ special class attributeFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | |
|
| ② | |
unchanged |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | x = 12L |
x = 12 |
| ② | x = 0755 |
x = 0o755 |
sys.maxintFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | from sys import maxint |
from sys import maxsize |
| ② | |
|
unicode() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | unicode(anything) |
str(anything) |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | u"PapayaWhip" |
"PapayaWhip" |
| ① | ur"PapayaWhip\foo" |
r"PapayaWhip\foo" |
callable() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | callable(anything) |
hasattr(anything, "__call__") |
zip() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | zip(a, b, c) |
list(zip(a, b, c)) |
| ② | d.join(zip(a, b, c)) |
unchanged |
StandardError() exceptionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | x = StandardError() |
x = Exception() |
| ② | x = StandardError(a, b, c) |
x = Exception(a, b, c) |
types module constantsFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | types.StringType |
bytes |
| ② | types.DictType |
dict |
| ③ | types.IntType |
int |
| ④ | types.LongType |
int |
| ⑤ | types.ListType |
list |
| ⑥ | types.NoneType |
type(None) |
isinstance global function (3.1+)FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | isinstance(x, (int, float, int)) |
isinstance(x, (int, float)) |
basestring datatypeFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | isinstance(x, basestring) |
isinstance(x, str) |
itertools moduleFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | itertools.izip(a, b) |
zip(a, b) |
| ② | itertools.imap(a, b) |
map(a, b) |
| ③ | itertools.ifilter(a, b) |
filter(a, b) |
| ④ | itertools.ifilterfalse(a, b) |
filterfalse(a, b) |
| ⑤ | from itertools import imap, izip, foo |
from itertools import foo |
sys.exc_type, sys.exc_value, sys.exc_tracebackFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | sys.exc_type |
sys.exc_info()[0] |
| ② | sys.exc_value |
sys.exc_info()[1] |
| ③ | sys.exc_traceback |
sys.exc_info()[2] |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | [i for i in 1, 2] |
[i for i in (1, 2)] |
os.getcwdu() functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | os.getcwdu() |
os.getcwd() |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | |
|
| ② | |
|
set() literalsFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | set([1, 2, 3]) |
{1, 2, 3} |
| ② | set((1, 2, 3)) |
{1, 2, 3} |
| ③ | set([i for i in a_sequence]) |
{i for i in a_sequence} |
buffer() global functionFIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | x = buffer(y) |
x = memoryview(y) |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | a ,b |
a, b |
| ② | {a :b} |
{a: b} |
FIXME intro
| Notes | Python 2 | Python 3 |
|---|---|---|
| ① | |
|
| ② | type(x) == T |
isinstance(x, T) |
| ③ | type(x) is T |
isinstance(x, T) |
| ④ | |
|