Check Python version from inside script? Run Pythons script in v2 compatibility mode?

Steve D'Aprano steve+python at pearwood.info
Fri Jul 7 03:53:38 EDT 2017


On Fri, 7 Jul 2017 04:30 pm, Ben S. wrote:

> Can I somehow check from inside a Python script if the executing Python engine
> is major version v2 or v3?

Yes you can, but generally speaking you shouldn't.

import sys
if sys.version_info >= (3,):  # the comma is important
    print("version 3")

else:
    print("version 2")


But keep in mind that your code must be syntactically valid for the running
version regardless of the result of the test. This will **NOT** work:

import sys
if sys.version_info >= (3,):  # the comma is important
    print("version 3")

else:
    print "version 2"  # Python 2 syntax


Earlier I said that in general you shouldn't test for the version. Normally you
should test for a specific feature, not for the version number. For example,
suppose I want to use the "reduce()" function. In Python 2 it is a built-in
function, but in Python 3 it is moved into the functools module.

Don't do this:

if sys.version_info >= (3,):
    from functools import reduce


This is better:

try:
    reduce
except NameError:
    # reduce no longer defined as a built-in
    from functools import reduce


That's now not only backwards compatible, but it is forward compatible: if
Python changes in the future to bring reduce back into the built-in functions,
your code will automatically keep working.

Dealing with syntax changes in hybrid version 2 + 3 code is quite tricky. It can
be done, but it is painful, even for experts.

> Additional question:
> Is there a way to execute a python script with v3 python engine in v2
> compatibility mode? I am thinking about a command parameter like (python.exe
> is v3.*):
> 
>   python.exe -execute_as_v2 myscript.py

No. Python 3 is always Python 3, and Python 2 is always Python 2. But what you
can do is install both, and then call 

python2.exe myscript.py

python3.exe anotherscript.py



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list