使用__future__还是将来编写与python2和python3兼容的代码是否更可取? [英] Is it preferable to use __future__ or future to write code compatible with python2 and python3?

查看:110
本文介绍了使用__future__还是将来编写与python2和python3兼容的代码是否更可取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者在某些特定情况下,一个比另一个更好?

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

到目前为止,我收集到的所有信息是,将来仅适用于> = 2.6或> = 3.3。

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

我拥有的当前代码非常基本,并且在python2和3上运行相同,除了使用print函数调用。但是,随着时间的推移,代码可能会变得更加复杂,我想从一开始就使用正确的方法来编写python2 / 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.

推荐答案

__ future __ 模块是Python内置的模块,用于允许程序员提前使用尚未被视为完整的功能集。尽管提供了某些功能(例如 eg ,__ future__ import print_function 中的)专门用于将Python 2程序移植到Python 3中,

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 __ 是唯一的,因为某些导入例如 print_function 实际上可以更改解释器接受的语法。

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

python-future 是第三方模块,是提供兼容性功能的几个模块之一。您也可以看看 6 ,虽然现在已经有些长了,但 python-modernize 。您很有可能会发现同时需要使用 __ future __ future

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.

您可能尚未考虑的另一种策略是将源转换为Python 2,该工具可以由 2to3 实用程序自动翻译。还有一个 lib3to2 会以其他方式转换,尽管我没有经验。

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.

这篇关于使用__future__还是将来编写与python2和python3兼容的代码是否更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆