Python version dilemma

Skip Montanaro skip at pobox.com
Mon Aug 27 15:47:30 EDT 2001


    > I have a set of scripts that use 2.1 syntax.  Now, I'd really like
    > these scripts to, when run by the 1.5 interpreter, gracefully state
    > that version 2 is required.  However, my code fails during the
    > compilation stage with the 1.5 interpreter (SyntaxError's and such),
    > and so never gets the chanced to execute a code portion that might
    > print a pretty (or at least useful) error message.

What you might want to do is push your version dependent code into separate
modules.  Suppose your module is named "mod".  In mod.py do this:

    try:
      from mod21 import *
    except SyntaxError:
      from mod15 import *

Alternatively, you could just push code into _mod and print a diagnostic if
you get a SyntaxError:

    try:
      from _mod import *
    except SyntaxError:
      print "requires Python 2.1 features"
      raise SystemExit

Of course, you can embellish either of these solutions any way you like.
I've used a solution similar to my first example just within my own
pythonrc.py stuff (I have a fairly heavyweight interactive startup), so that
I can get all the little ditties I'm used to in either Python 1.6 or 2.1.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list