Is it preferable to use __future__ or future to write code compatible with python2 and python3?

左心房为你撑大大i 提交于 2020-01-11 11:32:36

问题


Or are there specific situations where one is better than the other?

So far, all I gathered is that future is only available for >=2.6 or >=3.3.

The current code I have is very basic and runs the same on python2 and 3 except for the use of print function calls. However, the code may get more complex over time and I would like to use the right approach for writing python2/3 compatible code from the beginning.


回答1:


The __future__ module is built-in to Python, and is provided to allow programmers to make advance use of feature sets which are not yet regarded as complete. Although some of the features (e.g., from __future__ import print_function) are provided specifically to assist with porting Python 2 programs to Python 3, it is also used to give early access to advance features of any release.

__future__ is unique, in that some imports such as the print_function can actually change the syntax accepted by the interpreter.

python-future is a third-party module, one of several to provide compatibility features. You could also take a look at six, though it's now somewhat long in the tooth, and python-modernize. It's quite likely you will find that you need to use both __future__ and future together.

Another strategy you may not have considered is to convert your source to Python 2 that can be translated automatically by the 2to3 utility. There is also a lib3to2 that will translate the other way, though I have no experience with it.




回答2:


Python 2.7 will not be maintained past 2020, see https://pythonclock.org/

Thus, if you just started learning python, I would suggest you just use python 3 directly instead of using python 2 and importing __future__.




回答3:


Unless you have a very specific reason to support Python 2.x, then Python 3.x is the future. It's been over 10 years since it was released.

Python 2.7, the last of the 2.x series, is end of life'd in 2020. https://www.python.org/dev/peps/pep-0373/

TLDR: It's time to use Python 3



来源:https://stackoverflow.com/questions/49635526/is-it-preferable-to-use-future-or-future-to-write-code-compatible-with-pytho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!