Moving to Python 3.0 (part3)

Goto start of series | Goto next in series

I would like for easygui to run under both Python 2.6 and under version 3.0. But in the move to 3.0, changes have been made (both to the language and to the the standard library) that make it difficult for the same code to run under both versions.

The first thing that I did was to side-step the issues around the new print function.

  • I let 2to3 convert all of my old print statements to calls to the new print function.
  • I did a global text change of “print(” to “writeln(“.
  • I wrote a little writeln function.
def write(*args):
  args = [str(arg) for arg in args]
  args = " ".join(args)

def writeln(*args):

The result is code that uses neither the old print statement nor the new print function. Where I previously had

print a, b, c

I now have


In the future, when the day comes when everybody is running version 3+, I will simply change “writeln” back to “print” and I will have completely standard Python code.

A bit more tricky was the fact that in the standard library, “Tkinter” was renamed to “tkinter” and “tkFileDialog” was renamed to “tkinter.filedialog“.

To make code that will run under both 2.6 and 3.0, you have to find out which version of Python you’re running and then execute code that is appropriate to that version.

The python documentation for sys.hexversion says

sys.hexversion contains the version number encoded as a single integer. This is guaranteed to increase with each version, including proper support for non-production releases. For example, to test that the Python interpreter is at least version 1.5.2, use:

if sys.hexversion >= 0x010502F0:
# use some advanced feature
# use an alternative implementation or warn the user

So here’s what I did.

if sys.hexversion >= 0x030000F0:
 runningPython3 = True
 runningPython3 = False

if runningPython3:
 from tkinter import *
 import tkinter.filedialog as tk_FileDialog
 from Tkinter import *
 import tkFileDialog as tk_FileDialog

In my code, I changed all remaining occurrences of “tkFileDialog ” to “tk_FileDialog“.

Now I have code that runs under both version 2.6 and under version 3.0.

I was pretty lucky; my situation wasn’t too complicated. I’m sure there are other folks for whom the transition will be much more difficult. But if you’re doing some fairly simple and basic stuff with Python, what worked for me might be enough to work for you.

About these ads

3 thoughts on “Moving to Python 3.0 (part3)

  1. why didn’t you use a try/except statement to import tkinter

      from tkinter import *
      import tkinter.filedialog as tk_FileDialog
    except ImportError:
      from Tkinter import *
      import tkFileDialog as tk_FileDialog

Comments are closed.