• Home
  • Blog
  • Moving from python 2 to python 3

Moving from python 2 to python 3

Vincent Danen

September 01, 2019

With my move to PythonAnywhere a few weeks back, I got my Flask-based applications up and running quite easily (I have two, this blog and another application). Then I had a bit of a heart attack on Friday realizing that Python 2 will be EOL at the end of the year. I guess I've been hiding under a rock and far too busy with my other work -- I've not done much coding in a few years now. At any rate, this caused a bit of a late-night panic for me so I spent Saturday thinking I would start converting both applications to Python 3.

To my surprise, I completed both on Saturday as well. I was expecting to have to refactor and potentially rewrite more than I did, so come Saturday night I was more than pleased to realize that both were done and working as expected. There weren't even a lot of things that needed to be changed so if I'm being honest, more time was spent refactoring code to silence pylint warnings than actually getting things to work with Python 3.7. There were obvious things like using print('foo') instead of print 'foo' and I found the Cheat Sheet: Writing Python 2-3 compatible code to be exceptionally helpful.

This is a list of all I really needed to change:

  • print 'foo' to print('foo')
  • urllib.urlencode() to urllib.parse.urlencode()
  • needing to UTF-8 encode a string before using hashlib on it, so:'hashlib.md5(self.email.lower()).hexdigest() to hashlib.md5(self.email.lower().encode('utf-8')).hexdigest()
  • ConfigParser became configparser
  • sgmllib is gone, so someone helpfully made sgmllib3k which will work for now but likely I'll need to find a solution for the future since it won't be maintained
  • unicode() to str()
  • and using BeautifulSoup4 rather than BeautifulSoup

All in all, it was relatively painless and there wasn't a lot that needed to be changed.

There are probably a ton of little scripts that need to be updated, especially for the print changes, but this gives me some peace knowing it's not going to be that difficult to change existing Python 2 scripts to Python 3. For some reason I figured this would be a terrible thing to have to do (like the stories I've heard about Perl 5 to 6). Turns out it was not bad at all.

I was looking at doing things like 'Some {} to print'.format(thing) vs using 'Some %s to print' % thing but after some poking around and looking in particular at this StackOverflow question I figured that some things still work and are better left alone. I'm sure there are a ton of optimizations and things I can do to make my code better now that it's running on Python 3, but that's stuff I can do in the future be it another Saturday spent hacking on some code or over Christmas holidays.

Leave a Comment

Comments use MarkDown. Need help? MarkDown Cheatsheet