100% found this document useful (1 vote)
301 views4 pages

Python 2 Python 3

This document summarizes changes between Python 2 and Python 3, including changes to strings, printing, numbers, iterators, exceptions, and module renames. Key changes include strings being Unicode by default, the print function replacing print statements, division always returning a float, and exceptions now being classes instead of strings.

Uploaded by

Shubham Sati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
301 views4 pages

Python 2 Python 3

This document summarizes changes between Python 2 and Python 3, including changes to strings, printing, numbers, iterators, exceptions, and module renames. Key changes include strings being Unicode by default, the print function replacing print statements, division always returning a float, and exceptions now being classes instead of strings.

Uploaded by

Shubham Sati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 4

Moving from Python 2 to Python 3

Introduction This document is aimed at Python 2 programmers wishing to start devel-


oping using Python 3. The document lists those objects and idioms that have changed
between the versions, showing how to change from Python 2-style to Python 3.1-style.
It also lists some of the most useful new features in Python 3.1. Note that if you
want to convert an existing program or module, the place to start is with the 2to3 tool
(docs.python.org/library/2to3.html). For a complete introduction to the Python 3
language (covering both 3.0 and 3.1, and vastly more than there’s room for here), see
Programming in Python 3 (Second Edition) by Mark Summerfield, ISBN 0321680561
(www.qtrac.eu/py3book.html).

Strings and String Formatting Printing and Executing


Python 3 strings are Unicode; unicode() is gone New functions print(), exec(); execfile() is gone
Python 2 Python 3.1 Python 2 Python 3.1
s = unicode(x) s = str(x) print a, b, c print(a, b, c)
s = u"\u20AC" s = "\u20AC" print "%03d" % 7 print("{:03d}".format(7))
s = ur"\w" s = r"\w" print x, print(x, end=" ")
String % operator is deprecated; use str.format() print>>sys.stderr, x print(x, file=sys.stderr)
"{} {}".format(i, s) exec code exec(code)
"%d %s" % (i, s) "{0} {1}".format(i, s) exec code in globals exec(code, globals)
"{i} {s}".format(i=i, s=s) exec code in ( exec(code,
"{0[i]} {0[s]}".format( globals, locals) globals, locals)
"%(i)d %(s)s" % ( {'i':i, 's':s}) with open(file) as fh:
execfile(file)
{'i':i, 's':s}) "{i} {s}".format( exec(fh.read())
**{'i':i, 's':s})
"%(i)d %(s)s" % ( "{i} {s}".format( Numbers
locals()) **locals()) Division doesn’t truncate; long() is gone; octal
"%s-%s" % ("X", "X") "{0}-{0}".format("X")
literals must start with 0o (zero-oh)
"{:.2f}".format(3.142)
Python 2 Python 3.1
"%.2f" % 3.142 "{0:.2f}".format(3.142)
x = 5 / 2.0 # x==2.5 x = 5 / 2 # x==2.5
"{π:.2f}".format(π=3.142)
x = 5 / 2 # x==2 x = 5 // 2 # x==2
"%.4s" % "Prime" "{:.4}".format("Prime")
i = 2147483648L i = 2147483648
"{%d%%}" % 20 "{{{}%}}".format(20) j = long(i * 2) j = int(i * 2)
"%0*d" % (3, 7) "{:0{}}".format(7, 3) x = 0123 # x==83 x = 0o123 # x==83

Representational Form Iterators


Backticks are gone; use repr() or str.format() New next(); iterators must have __next__()
Python 2 Python 3.1 Python 2 Python 3.1
s = repr(x) x = iterator.next() x = next(iterator)
s = "{!r}".format(x) class Iterator: class Iterator:
s = `x`
s = "{0!r}".format(x) def __init__(self): def __init__(self):
s = "{z!r}".format(z=x) self.i = -1 self.i = -1
Force ASCII representation with ascii() def next(self): def __next__(self):
self.i += 1 self.i += 1
s = ascii(x)
s = `x` return self.i return self.i
s = "{!a}".format(x)
Removals and Replacements fn.func_defaults fn.__defaults__
An operator, an exception, a constant, some types, fn.func_dict fn.__dict__
several global functions, several dictionary meth- fn.func_doc fn.__doc__
ods, and some itertools functions are gone fn.func_globals fn.__globals__
Python 2 Python 3.1 fn.func_name fn.__name__
if a <> b: if a != b: obj.method.im_func obj.method.__func__
apply(fn, args) fn(*args)
obj.method.im_self obj.method.__self__
apply(fn, args, kwargs) fn(*args, **kwargs)
obj.method.im_class obj.method.__class__
if isinstance(x,
if isinstance(x, str): string.letters string.ascii_letters
basestring):
string.lowercase string.ascii_lowercase
x = memoryview(y)
x = buffer(y) string.uppercase string.ascii_uppercase
# this is similar
if hasattr(x, threading.Lock. \ threading.Lock. \
if callable(x):
"__call__"): acquire_lock() acquire()
fh = file(fname, mode) fh = open(fname, mode) threading.Lock. \ threading.Lock. \
if d.has_key(k): if k in d: release_lock() release()
for k, v in \ class Thing:
for k, v in d.items():
d.iteritems(): def __init__( class Thing:
for k in d.keys(): self, x): def __init__(
for k in d.iterkeys():
for k in d: self.x = x self, x):
for v in \ def __nonzero__( self.x = x
for v in d.values(): self): def __bool__(self):
d.itervalues():
for line in \ return \ return bool(self.x)
for line in file: bool(self.x)
file.xreadlines():
x = input(msg) x = eval(input(msg))
intern(s) sys.intern(s) Exceptions
f = itertools.ifilter( Catching exception objects requires the as key-
f = filter(fn, seq)
fn, seq) word; raising exceptions with arguments requires
m = itertools.imap( parentheses; strings cannot be used as exceptions
m = map(fn, seq)
fn, seq) Python 2 Python 3.1
z = itertools.izip( try: try:
z = zip(seq1, seq2)
seq1, seq2) process() process()
dir = os.getcwdu() dir = os.getcwd() except ValueError, \ except ValueError \
s = raw_input(msg) s = input(msg) err: as err:
print err print(err)
r = functools.reduce(
r = reduce(fn, seq) try: try:
fn, seq)
process() process()
reload(module) imp.reload(module)
except (MyErr1, except (MyErr1,
class MyErr( class MyErr( MyErr2), err: MyErr2) as err:
StandardError): Exception):
print err print(err)
sys.maxint sys.maxsize
raise MyErr, msg raise MyErr(msg)
for i in xrange(n): for i in range(n):
raise MyErr(msg). \
raise MyErr, msg, tb
with_traceback(tb)
Renamed Attributes and Methods raise Exception(
Implement __bool__() instead of __nonzero__() to raise "Error"
"Error")
return a custom class’s truth value generator.throw( generator.throw(
Python 2 Python 3.1 MyErr, msg) MyErr(msg))
fn.func_closure fn.__closure__ generator.throw( generator.throw(
fn.func_code fn.__code__ "Error") Exception("Error"))
Renamed Modules Python 3.1Idioms
Data read from a URL, e.g., using urllib.request. Tuples need parentheses in comprehensions; meta-
urlopen() is returned as a bytes object; use classes are set with the metaclass keyword; import
bytes.decode(encoding) to convert it to a string. the pickle and string I/O modules directly; lamb-
The bsddb (Berkeley DB library) is gone—but is da doesn’t unpack tuples; set literals are supported
avaliable from pypi.python.org/pypi/bsddb3. See (the empty set is set(); {} is an empty dict); sort-
PEP 3108 (www.python.org/dev/peps/pep-3108) ing is fastest using a key function; super() is better;
for module renaming details type-testing is more robust with isinstance(); use
Python 2 Python 3.1 True and False rather than 1 and 0
import anydbm Python 2 Python 3.1
import dbm
import whichdb L = [x for x in 3, 6] L = [x for x in (3, 6)]
import BaseHTTPServer class A: class A(
__metaclass__ = \ metaclass=MyMeta):
import \
import http.server MyMeta pass
SimpleHTTPServer
class B(MyBase): class B(MyBase,
import CGIHTTPServer
__metaclass__ = \ metaclass=MyMeta):
import __builtin__ import builtins MyMeta pass
import commands import subprocess try:
import ConfigParser import configparser import cPickle \
import Cookie import http.cookies as pickle import pickle
import cookielib import http.cookiejar except ImportError:
import pickle
import copy_reg import copyreg
try:
import dbm import dbm.ndbm
import cStringIO \
import DocXMLRPCServer
as StringIO import io
import \ import xmlrpc.server except ImportError:
SimpleXMLRPCServer import StringIO
import dumbdbm import dbm.dumb fn = lambda t: \
import gdbm import dbm.gnu fn = lambda (a,): \
abs(t[0])
abs(a)
import httplib import http.client fn = lambda a: abs(a)
import Queue import queue fn = lambda t: \
fn = lambda (a, b): \
import repr import reprlib t[0] + t[1]
a + b
import \ fn = lambda a, b: a + b
import robotparser
urllib.robotparser S = set((2, 4, 6))
S = {2, 4, 6}
import SocketServer import socketserver S = set([2, 4, 6])

import \ L = list(seq)
L = sorted(seq)
import test.support L.sort()
test.test_support
words.sort(
import Tkinter import tkinter words.sort(
lambda x, y:
import \ key=lambda x:
cmp(x.lower(),
urllib.request, \ x.lower())
import urllib y.lower()))
urllib.parse, \
class B(A): class B(A):
urllib.error def __init__(self): def __init__(self):
import \ super(B, self). \ super(). \
import urllib2 urllib.request, \ __init__() __init__()
urllib.error if type(x) == X:
import urlparse import urllib.parse if isinstance(x, X):
if type(x) is X:
import xmlrpclib import xmlrpc.client
while 1: while True:
process() process()
New in Python 3.1 General Notes
Dictionary and set comprehensions; * unpack- Python 3 often returns iterables where Python 2 re-
ing; binary literals; bytes and bytearray types; turned lists. This is usually fine, but if a list is real-
bz2.BZ2File and gzip.GzipFile are context man- ly needed, use the list() factory function. For ex-
agers; collections.Counter dictionary type; ample, given dictionary, d, list(d.keys()) returns
collections.OrderedDict insertion-ordered dictio- its keys as a list. Affected functions and methods
nary type; decimal.Decimals can be created from include dict.items(), dict.keys(), dict.values(),
floats filter(), map(), range(), and zip().
Python 2 Python 3.1 Most of the types module’s types (such as types.
d = {} LongType) have gone. Use the factory function
d = {x: x**3
for x in range(5): instead. For example, replace if isinstance(x,
for x in range(5)}
d[x] = x**3 types.IntType) with if isinstance(x, int).
S = set( Comparisons are strict—x < y will work for com-
S = {x for x in seq}
[x for x in seq]) patible types (e.g., x and y are both numbers or
Python 3.1 both strings); otherwise raises a TypeError.
a, *b = (1, 2, 3) # a==1; b==[2, 3] Some doctests involving floating point num-
bers might break because Python 3.1 uses David
*a, b = (1, 2, 3) # a==[1, 2]; b==3
Gay’s algorithm to show the shortest representa-
a, *b, c = (1, 2, 3, 4) # a==1; b==[2, 3]; c==4
tion that preserves the number’s value. For ex-
x = 0b1001001 # x==73
ample, 1.1 in Python 2 and 3.0 is displayed as
s = bin(97) # s=='0b1100001'
1.1000000000000001, and in Python 3.1 as 1.1.
y = int(s, 2) # y==97
u = "The " # or: u = "The \u20ac"
String Format Specifications
# or: u = "The \N{euro sign}"
v = u.encode("utf8") # v==b'The \xe2\x82\xac' str.format() strings have one or more replace-
w = v.decode("utf8") # w=='The ' ment fields of form: {Name!Conv:Spec}. Name iden-
x = bytes.fromhex("54 68 65 20 E2 82 AC") tifies the object to format. Optional !Conv is: !a
# x==b'The \xe2\x82\xac' (ASCII repr() format), !r (repr() format), or !s
y = x.decode("utf8") # y=='The ' (string format). Optional :Spec is of form:
z = bytearray(y) : Fill Align Sign # 0 Width , .Prec Type
z[-3:] = b"$" # z==bytearray(b'The $') Fill is any character except }. Align is: < (left), >
with bz2.BZ2File(filename) as fh: (right), ^ (center), or = (pad between sign and num-
data = fh.read() ber). Sign is: + (force), - (- if needed), or “ ” (space
counts = collections.Counter("alphabetical") or -). # prefixes ints with 0b, 0o, or 0x. 0 means
# counts.most_common(2)==[('a', 3), ('l', 2)] 0-pad numbers. Width is the minimum width. The
d = collections.OrderedDict( , means use grouping commas. .Prec is the maxi-
(("x", 1), ("k", 2), ("q", 3))) mum width for strs and number of decimal places
# list(d.keys())==['x', 'k', 'q'] for floats. Type is: % (percent), b (binary), d (deci-
dec = decimal.Decimal.from_float(3.75) mal), e or E (exponential), f (float) g or G (general
# dec==Decimal('3.75') float) n (localized) o (octal), x or X (hex). Every-
thing is optional, except that Fill requires Align.
Special Methods "{:*=+10.1f}".format(12345.67) # '+**12345.7'
"{:*>+10.1f}".format(12345.67) # '**+12345.7'
The slice methods (__delslice()__, __get-
"{:+010.1f}".format(12345.67) # '+0012345.7'
slice()__, __setslice__) are gone; instead __del-
"{:,.2f}".format(12345.678) # '12,345.68'
item()__, __getitem()__, and __setitem__ are
called with a slice object. An informIT.com
The methods __hex__() and __oct__() are gone; publication by
use hex() and oct(). To provide an integer, imple- Mark Summerfield.
ment __index__(). #3 Copyright  Qtrac Ltd. 2009.
License: Creative Commons Attribution-Share Alike 3.0 U.S.

You might also like