Stop writing Python 4 incompatible code

BartC bc at freeuk.com
Wed Jan 13 20:02:08 EST 2016


On 13/01/2016 07:30, Steven D'Aprano wrote:
> Quote:
>
>      With the end of support for Python 2 on the horizon (in 2020),
>      many package developers have made their packages compatible
>      with both Python 2 and Python 3 by using constructs such as:
>
>          if sys.version_info[0] == 2:
>              # Python 2 code
>          else:
>              # Python 3 code

> Better still, don't do version checks *at all*. There is almost never any
> need for a version check. Better is to use feature detection:
>
>
> try:
>      xrange  # Succeeds in Python 2.
> except NameError:
>      xrange = range

I was surprised recently by just how much incompatibility there was 
between Python 2 and 3. It wasn't just about print with parentheses and 
range instead of xrange.

I wanted to try out a jpeg decoder with PyPy and the three different 
ones I could find only worked with 2.x. Attempts to fix the 
incompatibilities usually lead to deeper mire.

In the end it was easier to put together my own version, which ran on 
all Pythons (2.7 to 3.4). It was surprisingly easy to do; no need for 
conditional version code.

(It was also smaller and considerably faster than the others even before 
I went tried PyPy. Using range in 2.7 instead of xrange didn't make much 
difference either.)

-- 
Bartc



More information about the Python-list mailing list