Friday 15:45–17:15 in Hall 7

Single-source Python 2/3

Mike Müller

Audience level:


Using a single source code to support Python 2 and Python 3 is a useful strategy to maintain backward compatibility and support the newest version of Python at the same time. This tutorial gives an overview over the major differences between Python 2 and 3. Based on these difference, two approaches are introduced. The creation on your own compatibility library is the first method. It has the advantage that there is no extra dependency. The disadvantage of this approach is that it you need to dive deep into the topic and that it can become a substantial effort. The second approach is to use an existing library. This tutorial introduces that makes many Python 3 features work in Python 2



Even though the first version of Python 3 has been released in 2008, at many places Python 2 or at last Python 2.7 will remain important for the foreseeable future. Therefore, many users need to maintain a library or an application for both major Python versions.

There are several strategies to support Python 2 and 3. Since maintaining two separate versions is not a real option, two major strategies have been established:

1.) automatic translation via 2to3 or 2.) the single-source approach with or without the help of an external library

In the beginning, it was though that the users will swiftly move to Python 3. This implies a one-time effort to port your Python 2 code to Python 3. As it turned out, this use case not as common as expected. Therefore, the automatic translation approach was moved into the install step. This technique is somewhat problematic because the translation is done at the time the user installs a library on th user's machine.

Over time the single-source approach became much more viable option. This tutorial focuses on this approach.


  • Overview of important Python 2/3 differences

    • print function
    • iterators everywhere
    • no apple-orange comparisons
    • integers without limits
    • strings are always unicode
    • new syntax
    • re-structuring of the standard library
    • build-in functions
  • Keep your tests ready

  • Writing your own compatibility layer

    • use modern Python 2 (exceptions, next)
    • future
    • version testing
    • re-defining built-ins
    • standard lib packports
    • handling strings and bytes
    • IO
  • Using

    • staring from scratch
    • starting from Python 2
    • starting from Python 3
    • catching exceptions
    • automatic conversion
    • porting philosophy


You should have Python 2.7 and Python 3.5 installed. Please install

conda install future


pip install future