Upgrading Python 2 to Python 3 – what to do with your programs?

Upgrading Python 2 to Python 3 – what to do with your programs?

Robbie Mosaic

As Python 3.0 was released in late year 2008, what would you do with your existing Python 2.x scripts to make them work on the new version?  For me, my experiences are as follows, and hope they’ll help you.

  1. "print" is no longer a keyword.  Use function print() instead.
  2. "except Exception, ex" should be changed to "except Exception as ex". (BTW, don’t confuse with VB.NET syntax "Catch ex As Exception".)
  3. Strings are UTF-16 now.  No need for u"something".  Note however, when reading from or writing to a file, mind the encoding.  If the file is opened in binary mode, the read() and write() functions use byte arrays, and its literal form is b"something".
  4. "cmp()" is gone and "list.sort()" no longer takes a comparison function as an argument.  Replacement for cmp() is to use "(a > b) – (a < b)" as mentioned in http://docs.python.org/dev/3.0/whatsnew/3.0.html.  Workaround for the second, for what I know now, is to implement a comparison class that implements __lt__() and __eq__(), wrap list objects as a list of objects of this new comparison class, and call sort().  Then put back the list of objects into the original list.  Note that the __cmp__() member method is no longer used.
  5. String formatting operator % is still there, but it is recommended that you use the format() string method.  Its simple use is "a: {0}, b: {1}".format(item0, item1).