[Python-ideas] sys.py3k

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Nov 5 03:08:33 CET 2012

On 4 November 2012 22:33, Steven D'Aprano <steve at pearwood.info> wrote:
> On 05/11/12 08:49, anatoly techtonik wrote:
>> if sys.py3k:
>>    # some py2k specific code
>>    pass
> Do you expect every single Python 3.x version will have exactly the same
> feature set? That's not true now, and it won't be true in the future.
> In my option, a better approach is more verbose and a little more work, but
> safer and more reliable: check for the actual feature you care about, not
> some version number. E.g. I do things like this:
> # Bring back reload in Python 3.
> try:
>     reload
> except NameError:
>     from imp import reload

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.

Checking the version rather than checking the attribute/name would
often be a mistake when comparing say Python 2.6 and Python 2.7 since
you're better off just sticking to 2.6 syntax and checking for
potentially useful names available under 2.7 as you describe.

On the other hand if you are distinguishing between 2.x and 3.x then
it is sometimes clearer and more robust to explicitly make a version
check rather than think hard about how to write code that works in
both cases (and hope that you remember your reasoning later). It also
makes it easier for you to clean up your codebase when you eventually
drop support for 2.x.


More information about the Python-ideas mailing list