Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Python 2.7 code that is as close to Python 3.x syntax as possible

Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question:

  • What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x?

I know that running python -3 will

Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix.

However, I'm interested in getting used to Python 3.x syntax while still using Python 2.7.

For instance, it seems that I should be using the following imports to my code:

from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import 

The above four __future__ import statements are required as of Python 3.0, but not required in 2.7 as described in Python 2.7.3's documentation 27.11. Future Statement Definitions

What else?

like image 782
Matthew Rankin Avatar asked May 09 '11 13:05

Matthew Rankin


People also ask

Are Python 2 and 3 compatible with each other?

# Python 2 and 3: forward-compatible from builtins import range for i in range(10**8): ... # Python 2 and 3: backward-compatible from past.

Is Python 2 and 3 very different?

Python 3 has an easier syntax compared to Python 2. A lot of libraries of Python 2 are not forward compatible. A lot of libraries are created in Python 3 to be strictly used with Python 3. Python 2 is no longer in use since 2020.

Can a program written in python 2 run in Python 3 can a program written using Python 3 run in Python 2?

Python 2.6 includes many capabilities that make it easier to write code that works on both 2.6 and 3. As a result, you can program in Python 2 but using certain Python 3 extensions... and the resulting code works on both.


1 Answers

Many modules these days get rewritten in a way that allows execution on both Python 2 and Python 3. This turns out to be not very hard at all, and in the future it will be very easy to just drop Python 2 support.

Take a look at the six module that helps with this task, encapsulating many of the differences in a convenient way:

Six provides simple utilities for wrapping over differences between Python 2 and Python 3.

Its website (and of course, code) lists a lot of ways to make this possible.

like image 96
Eli Bendersky Avatar answered Oct 18 '22 13:10

Eli Bendersky