Shall I worry about python2/3 compatibility when using library?

Cameron Simpson cs at cskk.id.au
Fri Aug 31 01:50:24 EDT 2018


On 30Aug2018 19:27, Stone Zhong <stone.zhong at gmail.com> wrote:
>I think the fact is:
>- There are still considerable amount of people still using python2
>- Python2 user will eventually upgrade to python3
>
>So any library not written in a compatible way will either break now for 
>python2 user, or will break in the future for python3 user. So I suppose all 
>library developer are writing compatible code, is that a fair assumption?

That depends on the developer and the library.

For myself, I try to write compatible code. For many things this is easy, and 
for most things this is possible, especially with the help of some kind of 
compatibility module like "six".

There are some tutorials on writing portable Python 3 code, and on porting 
Python 2 code.

I have a little module of my own "cs.py3" which covers most of the things I've 
needed to port; it aims to provide Python 3 flavoured versions of things. That 
way (a) my code expects Python 3 (where that matters) and (b) the code runs 
maximally efficiently under Python 3 because most of the things are just a 
direct import of the Python 3 builtin - the Python 2 code is the emulation (for 
want of a term).

Why my own? To some extent so I learn myself what's changed. Nothing like 
implenting something for Python 2 to match Python 3 for these things.

I'll assume you're aware of the main differences; if not we can elaborate.

Not everything can be done seamlessly, but you might be surprised how small an 
issue it usually is.

That said, I do have some modules which are Python 3 only. So far I think these 
are all modules doing byte level parsing of binary data - this is outstandingly 
easier in Python 3 - you're never unsure if you're dealing with bytes versus 
text (str). I was looking at making them Python 2 capable, but the pain level 
was too high.

My advice: try to be portable (same code good for both 2 and 3), try to port 
when this is an issue, try to use third party modules which work with both 2 
and 3 when you have a choice, look at the 'six" module if things get harder.

And aim for Python 2.7 - this goes a long way to making 2 and 3 easy to work 
with. The fursther back you go in 2.x the harder it gets.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list