views:

98

answers:

2

I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code:

import sys
if sys.version < '2.6':
    raise Exception( "python 2.6 required" )

However, the 2.4 interpreter chokes on the with keyword (later in the script) because it doesn't recognize the syntax, and it does this before it evaluates my check.

Is there something in Python analogous to Perl's BEGIN{} block?

+3  A: 

Perhaps someone has a better answer, but my first thought would be to have a separate script to perform the check, then import the "real" script once the check has passed. Python won't check the syntax until the import happens.

import sys
if sys.version < '2.6':
    raise Exception( "python 2.6 required" )

import myscript  # runs myscript
orangeoctopus