[Tutor] 2.x and 3.x in one code base [was Re: PYTHONHASHSEED, -R]

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jul 30 15:07:13 CEST 2013


On 29 July 2013 22:08, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> Steven wrote:
>>
>> Notice that I always test for the feature, not for the version number. This is
>> defensive programming -- maybe some day my code will be running on an
>> almost-but-not-quite compatible version of Python, and version checks will give
>> the wrong idea. E.g. "AmazingPython 1.1" might have the same
>> functionality of Python 3.3, but I'd never know it if I just check the
>> version number.
>
> Good point:
>
> Python 2.7.2 (1.9+dfsg-1, Jun 19 2012, 23:23:45)
> [PyPy 1.9.0 with GCC 4.7.0] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> And now for something completely different: ``why did you guys have to make the
> builtin fortune more interesting than actual work? i just catched myself
> restarting pypy 20 times''
>>>>> import sys
>>>>> sys.version
> '2.7.2 (1.9+dfsg-1, Jun 19 2012, 23:23:45)\n[PyPy 1.9.0 with GCC 4.7.0]'
>
> There are probably situations where Python 2.x and pypy are not quite the same. So just using "if sys.version == '2' " is indeed not a good idea. E.g., yesterday I used pypy to run tests (using nosetests) and one test failed. Sliiight difference in ordering and layout of the actual result.

If you do want to test the Python version directly then you should use
sys.version_info rather than sys.version:

$ python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)
>>> sys.version_info[:2]
(2, 7)
>>> sys.version_info >= (2, 7, 1)
True
>>> sys.version_info >= (3, 3)
False

AmazingPython, pypy etc. should use sys.version_info consistently with
CPython to indicate the version of the Python language, not the
version of the implementation.

PEP 421 adds sys.implementation to the language so that AmazingPython
1.1 can store its version there:
http://www.python.org/dev/peps/pep-0421/


Oscar


More information about the Tutor mailing list