Porting Python 2 Code to Python 3

Python 3 was released in Dec 2008 – almost 10 years and we still found a lot of python 2.7 developers. Python 3 is Not backward compatible with Python 2. Most language features are the same,  some detail has changed and many deprecated features have been tided up and removed

The main reason today to work with python 2.7 is to keep maintain a big project written in python 2. If you start a new project you definitely choose python 3.

It is not hard to port python 2 code to python 3 – you can do it manually or use the utility 2to3.py.

The Print Function

The first thing everyone notices about Python 3 is that the print statement is no longer a, um, statement: it is a built-in function.  The effect is that we now have to put parentheses around the thing we wish to print.

Most commonly used for displaying a comma separated list (Objects are stringified)

Has several named arguments

  • end= characters to be appended, default is ‘\n’ (newline)
  • file= file object to be written to, default is sys.stdout
  • sep= separator used between list items, default is a single space

Also format changed but you can use the old format (using %)

Simple keyboard (stdin) input

raw_input is replaced by input. The input statement reads from stdin, which is usually the keyboard but may have been redirected

Misc Changes

  • The tests <> and cmp are no longer supported – both statements throws errors – use ==, !=

 

  • Non Ascii Names are allowed – use magic comment for that

 

  • Backticks are removed – use repr instead

  • New format for octal numbers:

  • Trailing L is no longer used – ints and long are the same
  • True, False, None are now keywords (In Python 2 they could be redefined)

 

Strings in python 3

  • Multi-byte characters
  • \unnnn –  two-byte Unicode character
  • \Unnnnnnnn –  four-byte Unicode character
  • \N{name}  –  a named Unicode character
  • The old Python 2 u”…” prefix is no longer supported

bytes() and bytearray()

used for low level interfacing, convert to string using decode:

Opening a file in binary mode returns a bytes object. Convert from a string using string.encode()

String formatting

Like printf in C, using the format method:

 

Collections

  • The format when printing a set changed in python 3

  • Dictionary methods  iterkeys(), itervalues(), iteritems() removed
  • Return values from keys(), values(), and items() are view objects
  • map and filter return iterators (instead of list in python 2)

in python 2:

in python 3:

 

Forcing a user to supply named arguments

You can use * to force a user to supply named arguments:

Function Annotations 

You can add documentation to the parameters and the return value:

variables in nested functions:

If we define a variables with the same name in a different scopes it may confuses the interpreter for example:

This code will fail with the error: UnboundLocalError: local variable ‘b’ referenced before assignment

To fix this you need to declare b as global or nonlocal

nonlocal

global

 

 Exceptions

Each exception has an arguments attribute stored in a tuple. The number of elements, and their meaning varies

The raise and except syntax changed and we throw only Exception objects (in python 2 you can throw string)

 

Properties and decorators

The property() built-in function defines get, set, delete, and docstring methods for a specific attribute

some of the changes are also supported in python 2 and using the back port option you can make the porting process easier

 

Tagged

Leave a Reply

Your email address will not be published. Required fields are marked *