Experience on Migrating Django App from Python 2 to Python 3


I got requirement lately to migrate existing API project code that was built using Django 1.10 and Python 2.7 and upgraded it to Django 2.1 and Python 3.7. As you may already know that Python 2.7 will meet end of support at the end of 2019.

So we need to say goodbye to Python 2.7 ASAP!

At first I thought it will be straightforward because my assumption that I don’t have special code that may break the code from Python 2 to Python 3.

But in reality I got some incompatibilities and error because of Python 2 and 3 differences so there are things I need to update. But luckily, not much work I need to do to make the existing code to work with Python 3.

Here things I found on migration relate with Python version incompatibility :

  • Python import
    Python 2 allows us to use relative module import like import _constants, but Python 3 enforce to use absolute path, so I must change it to import api.views._constants
  • map(lambda …
    On Python 2.7, map will return list but in Python 3 it returns map object, not list anymore. So i need to wrap map object inside list() function to make it returns list.
  • has_key()
    Function dict.has_key() is not supported anymore in Python 3 so I changed it to function dict.__contains__
  • try except syntax
    Before code like below worked well:
    except ZeroDivisionError, e:
    But now must change to :
    except ZeroDivisionError as e:
  • ‘string’.encode(‘utf-8’)
    Encode from string is not supported anymore so we can just remove encode(‘utf-8’)
  • dict.iteritems()
    We need to change it to dict.items()
  • basestring
    Need to replace it with str
  • str(bytevar)
    Conversion from byte to string need to change to bytevar.encode(‘utf-8’)
  • dict.items() + dict.items()
    Concatenation of dict items will not work anymore but need to wrap it inside list like below:
    list( dict.items() ) + list( dict.items() )