编写尽可能接近 Python 3.x 语法的 Python 2.7 代码 [英] Writing Python 2.7 code that is as close to Python 3.x syntax as possible

查看:53
本文介绍了编写尽可能接近 Python 3.x 语法的 Python 2.7 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Django 尚不支持 Python 3.x,我使用的是 Python 2.7.但是,我想继续尽可能地熟悉新的 Python 3.x 语法.这让我想到了这个问题:

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:

  • 编写与 Python 3.x 尽可能兼容的 Python 2.7 代码的最佳方法是什么?

我知道运行 python -3

警告 2to3 无法轻松修复的 Python 3.x 不兼容性.

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

但是,我有兴趣在仍然使用 Python 2.7 的同时习惯 Python 3.x 语法.

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

以上四个 __future__ import 语句从 Python 3.0 开始是必需的,但在 2.7 中不需要,如 Python 2.7.3 的文档 27.11.未来声明定义

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

还有什么?

推荐答案

如今许多模块都以允许在 Python 2 和 Python 3 上执行的方式重写.未来很容易放弃对 Python 2 的支持.

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.

查看有助于完成此任务的 six 模块,其中包含了许多不同之处一个方便的方法:

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

Six 提供了简单的实用程序包装之间的差异Python 2 和 Python 3.

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.

这篇关于编写尽可能接近 Python 3.x 语法的 Python 2.7 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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