Writing Python 2.7 code that is as close to Python 3.x syntax as possible

Solution 1:

Many modules these days get rewritten in a way that allows execution on both Python 2 and Python 3. This turns out to be not very hard at all, and in the future it will be very easy to just drop Python 2 support.

Take a look at the six module that helps with this task, encapsulating many of the differences in a convenient way:

Six provides simple utilities for wrapping over differences between Python 2 and Python 3.

Its website (and of course, code) lists a lot of ways to make this possible.

Solution 2:

Put the following code into a py3k.py module and import it like this: from py3k import *. You need to put it in every file though, but you can even leave it there if nobody uses Python 2.x anymore or you could just search & replace the import line with whitespace and then remove the file.

try:
    from future_builtins import *
except ImportError:
    pass

try:
    input = raw_input
    range = xrange
except NameError:
    pass

And this is how my template file looks:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""

"""

from __future__ import division, absolute_import, \
                       print_function, unicode_literals
from utils.py3k import *  # @UnusedWildImport


#