Wednesday, July 17, 2019

[Python] The issues of converting Python2 to Python3

If you are working on converting Python2 source code to Python3, there are some issues you will encounter sooner or later. I arrange my part here and will continue to update it as follows:

Division Operators in Python2 and Python3 are different

# A Python 2.7 program
print 5/2
2

# A Python 3.5 program
print (5/2)   <== have to use parentheses with print function
2.5

AttributeError: module 'itertools' has no attribute 'izip'

# https://www.cnblogs.com/simplezhuo/p/9811369.html
Change using from itertools.izip() to zip()

TypeError: 'KeysView' object does not support indexing

# https://stackoverflow.com/questions/45426579/typeerror-keysview-object-does-not-support-indexing
In [80]: d={'a':1, 'b':2}
In [81]: d.keys()
Out[81]: dict_keys(['a', 'b'])
In [82]: d.keys()[0] <== Cannot use indexing in KeysView in Python3

In [84]: list(d.keys())[0]  <== It is OK now

The issue of Python 2 and 3 csv reader:

# https://stackoverflow.com/questions/5180555/python-2-and-3-csv-reader
import sys

if sys.version_info[0] < 3: 
    infile = open(filename, 'rb')
else:
    infile = open(filename, 'r', newline='', encoding='utf8')

No comments: