robert
robert

Reputation: 34408

Perl's BEGIN{} block in Python

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?

Upvotes: 4

Views: 1045

Answers (2)

Donald Miner
Donald Miner

Reputation: 39903

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

Upvotes: 3

Related Questions