The latest version of python 2.x i.e.2.7 was released on 2010 and there will not be any 2.x releases after that.Python 3.0 was released in 2008.All improvements in python standard libraries will be made available through 3.x releases."Python 3000" or "Py3K", was the first backwards incompatible Python release. Python 3.0 was released with more changes than any other individual former releases.The latest python version is 3.5.0.There are few things to keep in mind if you want to make your code compatible with both Python 2.x and 3.x. Above all the choice between the versions depends only on what you want to achieve.

 

1. Understand the difference between 2.x and 3

i. Print statement

The biggest difference between the two is the print statement.The print statement of Python2 is replaced with the print() function.The object should be folded inside the parenthesis to get it printed.Python 3 way of calling print will work fine in python 2 and the reverse process will result in raising a 'SyntaxError'.

 

Python 2.x

print 'The 2.x way of print'
print('The 3.x way of print')
Result
The 2.x way of print
The 3.x way of print
 
Python 3.x
print('The 3.x way of print')
print 'The 2.x way of print'
Result
'The 3.x way of print'
File "", line 1
    print 'Hello, World!'
                    ^
SyntaxError: invalid syntax
 
Note:

If we have multiple objects inside the parentheses, it will create a tuple, since print is a "statement" in Python 2, not a function call.

print('a', 'b')
print 'a', 'b'

('a', 'b')
a b

ii. Xrange

Python 2.x uses xrange() to create iterable object.,in a list comprehension or for loop.range() has advantage over xrange() since it is generally faster if you have to iterate over it only once.In python 3 xrange() raises a NameError.range() was introduced like the xrange() function so that previously existed xrange() function does not exist anymore.

import timeit

n = 50
def test_range(n):
    for i in range(n):
        pass

def test_xrange(n):
    for i in xrange(n):
        pass 

Python 2

print '\ntiming range()'
%timeit test_range(n)

print '\n\ntiming xrange()'
%timeit test_xrange(n)

timing range()
1000 loops, best of 3: 433 µs per loop


timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('\ntiming range()')
%timeit test_range(n)

timing range()
1000 loops, best of 3: 520 µs per loop

print(xrange(10))

--------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in ()
----> 1 print(xrange(10))

NameError: name 'xrange' is not defined

 

iii. Exceptions

The non-parenthesized exceptions are axed from Python3 whereas both notations are accepted in the Python2 versions.

Python 2

raise RuntimeError, "runtime error"

.....................
RuntimeError: runtime error

raise RuntimeError("runtime error")

.....................
RuntimeError: runtime error

Python 3

raise RuntimeError, "runtime error"

.....................
SyntaxError: invalid syntax

raise RuntimeError("runtime error")

.....................
RuntimeError: runtime error

 

Note:

There is a slight change in Python3 for handling the exceptions as well.The "as" keyword has been introduced in the 3.x versions for better handling of exceptions.

 
Python2
try:
    NameError
except NameError, err:
    print err, 'custom message'
    
name 'NameError' is not defined custom message
 
Python3
try:
    NameError
except NameError as err:
    print err, 'custom message'
    
name 'NameError' is not defined custom message
 
 

iv. List comprehensions and global namespace leak

List comprehensions do not support the syntactic form anymore[... for item in item1, item2, ...]. Use [... for item in (item1, item2, ...)] instead.The for loop variables in Python3 are not allowed to escape into the global namespace anymore.

 

Python2

i = 1
print 'before the loop: i =', i

print 'list comprehension: ', [i for i in range(5)]

print 'after the loop: i =', i

before the loop: i = 1
list comprehension:  [0, 1, 2, 3, 4]
after the loop: i = 4

Python3

i = 1
print 'before the loop: i =', i

print 'list comprehension: ', [i for i in range(5)]

print 'after the loop: i =', i

before the loop: i = 1
list comprehension:  [0, 1, 2, 3, 4]
after the loop: i = 1

 

You can have a look on the doc to see the other changes.

 

2. Having good test coverage for the existing code

There may be code reworking once you started to shift from 2.x version to 3 and of course bugs will follow you.You should make sure that the bugs are actually caused by the tools,not from the actual code. It will be good to have a test coverage of 80-90 percent of your code to get over the hurdle smoothly.Have a look on this package for better results.

 

3. Update the existing code

Understanding the difference between the two versions is important.Once you know the changes, you can start updating your code to support the Python3. There are many tools available to fulfill the need.Modernize and Futurize are the main tools we use to update the code.

You need to run the tool you choose over the test suite first to see the changes and make sure the transformation is accurate.You need to work on the code only once the test suite is transformed and all tests are passed as expected.

Even though we are using tools to update the code, there are few things you need to update manually to get the full support of Python 3. You need to go through the tool’s documentation to  identify what the tool does and what should be fixed manually.

 

All int divisions result as float in Python3. The same was accomplished in Python2 using the following import:

from __future__ import division

 

4. Identifying the blocking dependencies

Once the code have been updated to support the new version,you should identify the blocking dependencies.You can use caniusepython3 to identify the blocking projects since these also need to be ported.The caniusepython3 also provides code which you can integrate into your test suite.

 

If you want to start a new project,go with Python3 because most of the important packages are ported to support the new version and there are some new features like bytes v/s Unicode string and fixes for some serious issues.There are still large community of users for Python 2.x and it may take some time for Python 3.x to get familiar.

 
 
Subscribe to our newsletter. Get updates on awesome happenings in the technology world!
Newsletter subscription successfull! Something went wrong! Email is already registered!

TAGS