[Python-ideas] sys.py3k

Steven D'Aprano steve at pearwood.info
Mon Nov 5 07:30:09 CET 2012

On Mon, Nov 05, 2012 at 02:08:33AM +0000, Oscar Benjamin wrote:

> There are certain cases where explicitly checking the version makes
> sense. I think that Python 3 vs Python 2 is sometimes such a case.
> Python 3 changes the meaning of a number of elementary aspects of
> Python so that the same code can run without error but with different
> semantics under the two different version series.

You can test for that without an explicit version check.

if isinstance(map(lambda x: x, []), list):
    # Python 2 semantics
    # Python 3 semantics

This now guards you against (e.g.) somebody backporting Python 3 
semantics to "Python 2.8" (it's opensource, somebody could fork 
CPython), or running your code under "FooPython" which has 3.x semantics 
and a 1.x version number.

This is more work than just mechanically looking at the version number, 
but it's not that much more work, and is more reliable since it 
explicitly checks for the feature you want, rather than an implicit 
check based on the version number.

In any case, arguments about defensive coding style are getting 
off-topic. The point is that there are various ways to test for the 
existence of features, and adding yet another coarse-grained test 
"sys.py3k" doesn't gain us much (if anything).


More information about the Python-ideas mailing list