- August 29, 2018
- Posted by: Mahesh Kulkarni
- Category: Blogs

There is a lot of fear, uncertainty and doubt when it comes to migrating to a higher version of any language. Python 3, which is into existence for more than 7 years now, is a newer version of Python 2. Python 3 may or may not necessarily be compatible with the implementations done in Python 2. However, many of us might want to think about migrating to Python 3 as the deadline for Python 2 will approach soon.
The Python 2 end of life date is confirmed to be in the year 2020. Also, there were very few dependencies that were compatible with Python 2 only, apparently very small or those which had Python 3 we could move to. Currently, there is no “right” or “wrong” between “Python 2.x” and “Python 3.x” as long as you have the support for python libraries that you are planning to use in your project. But before you think to make a transition to this higher version of Python, you might want to know insights of this migration being introduced at first place.
There can be possibly 2 approaches for migration:
Supporting only Python 3 –
This is when the support for previous python version is to be removed entirely. This is a bit easier task and less cumbersome. For this, you can use Python 2to3 automatic conversion which will convert python code from 2 to 3 for most of the changes and rest of the code issues can be resolved manually in Python 3 code. However, in the end, it does require a code clean up and hence you would want to change the code all by yourself.
Supporting Python 2 and 3 both-
While maintaining both Python versions can be possible, two branches need to be maintained for that purpose. Maintaining the code which supports only Python 2 at one place and the one which supports only Python 3 at another place is doable but not recommended. If you decide to maintain both Python 2 and Python 3 version, you are increasing difficulty as only fewer bug fixes will be available for the former.
The main difference will not just be in syntax but the behavior of the code, absence/presence of some libraries in both the versions and its semantics. So basically, the migration strategy to be implemented is entirely dependent on the requirement.
Here’s a glimpse of the changes which are required for migrating Python 2.7 to Python 3.6.5-
Unicode and str:
In Python 2.x- str was used for both text and binary which used to make the code brittle and work inconsistently. However, now Python 3 has made a clear distinction between text and binary data. Unicode and str were different in Python 2, are now the same in Python 3. Implicit str type is ASCII in Python 2, while its Unicode in Python 3.
Syntax for “Print” statement:
The noticeably trivial change is in the syntax for “print”. For Python 2.x, there is no issue if additional parentheses used, however, Python 3.x would raise Syntax Error if double quotes are not enclosed with parentheses.
__future__ module:
With the introduction of Python 3.x, few keywords and features which are incompatible with Python 2.x are, e.g. integer division behavior, then one should import
__future__ module in Python 2.x in order to have Python 3.x support in your code.
from __future__ import division
Integer division:
Integer division behavior is changed slightly in the higher version of Python. While some changes might go unnoticed, here’s an example to help understand the change in Python 3.x.
Python 2.x-
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Python 3.x-
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Xrange:
Python 3 raises NameError for xrange because the dedicated xrange function does not exist anymore. Now, range() is implemented in Python 3.x just like the xrange() function in Python 2.x
Raising exceptions:
Python 3.x will raise a SyntaxError if the exception argument is not enclosed in parentheses unlike Python 2.x where this was acceptable. Also, unlike Python 2.x, there have been some improvements PEP- 3134 [*] to make debugging easier, as it puts less burden on developers for being traceback-aware. This is one of the most unpopular features of Python 3.x.
The next() function and .next() method:
.next() method is no more present in Python 3.x and raises AttributeError and the next() function remains same in Python 3.x as that of Python 2.x.
Python 2.x
print 'Python', python_version()
my_gen = (letter for letter in 'xyz')
next(my_gen)
my_gen.next()
Output-
Python 2.7.6
'y'
Python 3.x
print('Python', python_version())
my_gen = (letter for letter in 'xyz')
next(my_gen)
Output-
Python 3.4.1
'X'
my_gen.next()
--------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-125f388bb61b> in <module>()
----> 1 my_gen.next()
AttributeError: 'gen' object has no attribute 'next'
Parsing user inputs via input():
One issue in Python 2 was fixed in Python 3 with respect to input() function. In Python 2.x, in order to have other types than strings, we had to use raw_input(), which was a dangerous behavior. This was thankfully fixed in Python 3, so as to always store the user inputs as strobjects.
Returning iterable objects instead of lists:
Python 2.x used to return lists for some methods and functions , while now in Python 3.x returns iterable objects. But for those situations, wherein we really need the list-objects, list() function can be used to convert into list.
Python 2.x
print 'Python', python_version()
print range(5)
print type(range(5))
Output-
Python 2.7.6
[0, 1, 2,3,4,5]
<type 'list'>
Python 3.x
print('Python', python_version())
print(range(5))
print(type(range(5)))
print(list(range(5)))
Output-
Python 3.4.1
range(0, 5)
<class 'range'>
[0, 1, 2,3,4,5]
Here’s the list of few more functions and methods which are commonly used and don’t return lists anymore:
- zip()
- map()
- .values() method in dictionary
- .items() method in dictionary
- .keys() method in dictionary
Banker’s Rounding:
There is a better way of rounding up to avoid partially with large numbers. In Python 3, now, round-off functionality is changed when it results it in a tie (that is, .5) at the last significant digits by rounding off to nearest even number. For more information, see the refer these Wikipedia articles and paragraphs:
- https://en.wikipedia.org/wiki/Rounding#Round_half_to_even
- https://en.wikipedia.org/wiki/IEEE_floating_point#Roundings_to_nearest
Python 2.x
print 'Python', python_version()
Python 2.7.12
round(14.5)
15.0
round(17.5)
18.0
Python 3.x
print('Python', python_version())
Python 3.5.1
round(14.5)
14
round(17.5)
18
Summary
Switching from Python 2 to Python 3 can be worthwhile for Python programmers since there have been few improvements in Python 3. But before doing it, it’s fruitful to check that the libraries your requirement depends on are supported in Python 3 as well. As the days pass on, the proportion of usage of Python 3 is surely going to increase than Python 2. The migration is happening gradually, but it is underway. You can still successfully write efficient and useful code using any python version. But it is a nice idea to be aware of the material differences between Python 2 and Python 3.
If your code is a reusable package or a framework, then you can drop the support for older python version completely without losing its performance or functionality. This is not at all. A lot more of changes have been done and it’s a good practice to get a thorough idea through the documentation beforehand. I also suggest to check out Brett Cannon’s slides and this migration guide PDF mentioned in Philip Semanchuk’s white paper. Keep Calm and Keep Coding!!
Usually I do not learn article on blogs, but I wish to say that this write-up very compelled me to check out and do it! Your writing style has been surprised me. Thanks, very nice post.|
I am really enjoying the theme/design of your web site. Do you ever run into any browser compatibility problems? A couple of my blog readers have complained about my site not operating correctly in Explorer but looks great in Firefox. Do you have any recommendations to help fix this issue?|
Appreciating the time and energy you put into your blog and detailed information you present. It’s great to come across a blog every once in a while that isn’t the same old rehashed information. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.|
Hello very cool web site!! Man .. Excellent .. Amazing .. I will bookmark your web site and take the feeds also? I’m satisfied to search out so many useful information here within the submit, we want develop more strategies in this regard, thank you for sharing. . . . . .|
Hi I am so glad I found your blog, I really found you by error, while I was looking on Askjeeve for something else, Anyways I am here now and would just like to say thank you for a tremendous post and a all round interesting blog (I also love the theme/design), I don’t have time to read it all at the minute but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work.|
Hi, I do believe this is an excellent web site. I stumbledupon it 😉 I’m going to come back once again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide others.|
I’m really inspired with your writing abilities and also with the layout to your blog. Is this a paid topic or did you modify it yourself? Anyway keep up the excellent high quality writing, it’s rare to see a nice blog like this one today..|
Hey terrific website! Does running a blog similar to this take a massive amount work? I’ve absolutely no understanding of computer programming however I had been hoping to start my own blog soon. Anyway, if you have any suggestions or tips for new blog owners please share. I know this is off subject but I simply needed to ask. Many thanks!|
Usually I don’t learn post on blogs, but I would like to say that this write-up very pressured me to try and do so! Your writing style has been amazed me. Thank you, very great post.|
Hey! This is my first comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that go over the same subjects? Thanks a ton!|
If some one needs to be updated with most recent technologies therefore he must be visit this site and be up to date every day.|
Hello There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly return.|
It’s really a cool and helpful piece of information. I’m glad that you just shared this helpful info with us. Please stay us up to date like this. Thank you for sharing.|
Saved as a favorite, I like your site!|
We’re a group of volunteers and starting a new scheme in our community. Your website provided us with valuable information to work on. You’ve done a formidable job and our whole community will be thankful to you.|
whoah this blog is magnificent i like studying your articles. Keep up the great work! You understand, lots of individuals are looking round for this information, you can aid them greatly. |
Hi! I’ve been following your website for a long time now and finally got the bravery to go ahead and give you a shout out from Humble Texas! Just wanted to tell you keep up the fantastic work!|
I must thank you for the efforts you have put in penning this website. I’m hoping to see the same high-grade content from you later on as well. In fact, your creative writing abilities has encouraged me to get my own, personal site now ;)|
Very nice blog post. I definitely appreciate this website. Continue the good work!|
Hello There. I found your blog the use of msn. That is an extremely smartly written article. I’ll make sure to bookmark it and return to read more of your helpful info. Thanks for the post. I will certainly comeback.|
Useful information. Lucky me I found your web site by accident, and I am stunned why this coincidence didn’t came about earlier! I bookmarked it.|
Thank you for every other informative site. The place else could I get that type of information written in such a perfect way? I have a project that I am just now running on, and I’ve been on the glance out for such info.|
Somebody necessarily help to make seriously posts I’d state. That is the very first time I frequented your website page and to this point? I amazed with the research you made to make this particular submit extraordinary. Fantastic task!|
I want to to thank you for this excellent read!! I certainly enjoyed every bit of it. I have got you saved as a favorite to look at new stuff you post…|
Hey there, You have done an incredible job. I will certainly digg it and personally suggest to my friends. I’m sure they will be benefited from this website.|
Fantastic web site. A lot of useful info here. I am sending it to some friends ans also sharing in delicious. And obviously, thanks in your effort!|
Awesome blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your design. Kudos|
Really when someone doesn’t be aware of afterward its up to other users that they will assist, so here it happens.|
Currently it looks like Drupal is the best blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?|
This is my first time pay a visit at here and i am truly impressed to read all at alone place.|
I’m not sure where you are getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic info I was looking for this information for my mission.|
Magnificent website. Lots of useful information here. I’m sending it to some pals ans also sharing in delicious. And obviously, thank you for your effort!|
It’s amazing to go to see this web page and reading the views of all colleagues about this piece of writing, while I am also eager of getting experience.|
Awesome blog! Do you have any tips and hints for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any suggestions? Cheers!|
An attention-grabbing discussion is worth comment. I think that you need to write more on this topic, it won’t be a taboo subject however typically persons are not enough to talk on such topics. To the next. Cheers