Stop writing Python 4 incompatible code

Chris Angelico rosuav at gmail.com
Wed Jan 13 20:21:23 EST 2016


On Thu, Jan 14, 2016 at 12:02 PM, BartC <bc at freeuk.com> wrote:
> 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.

This implies that there are many differences between 2.x and 3.x.

> 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.

But this implies that the differences are pretty simple. Which
argument are you putting?

The biggest difference between 2.x and 3.x is the handling of text vs
bytes. This is a very important distinction, but for a lot of
programs, it's not difficult; most of what you'll be using will be
text, and the only difference is that the 3.x version of your program
can handle all of Unicode. If you open any files, you might need to
specify encoding="utf-8" or encoding="ascii" or something, but that's
about the only issue.

> (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.)

Yeah, the effectiveness of xrange over range isn't significant on
smallish lists. And PyPy can optimize all sorts of things. If I'm
writing 2/3 compatible code, I'll usually just use range() everywhere,
unless I know for sure that the lists are going to be huge.

ChrisA



More information about the Python-list mailing list