问题描述
我正在编写一个模块,让我在 python 3 中编写代码,但仍然在 2 中运行它.实际上它看起来非常简单......我还应该添加什么?从我对交互式解释器的(有限的)抨击来看,未来的导入不会影响 python 3 并且被视为多余的.
I am writing a module to let me write code in python 3, but still run it in 2. It looks surprisingly easy actually... anything else I should add? From my (limited) flailing on the interactive interpreter, the future imports do not affect python 3 and are viewed as redundant.
# _2or3.py
'''
Common usage:
from __future__ import print_function, nested_scopes, division, absolute_import, unicode_literals
from _2or3 import *
'''
import sys
if sys.version[0] == '2':
range = xrange
input = raw_input
显然有些事情你不能做,而你通常可以在 3 中做(比如字典压缩),并且语言之间有一些问题(比如字节码.看起来你永远不应该使用字节)
Obviously there are some things you cannot do that you would normally be able to do in 3 (like dictionary compressions), and there are a few gotchas between the languages (like bytecodes. It looks like you should NEVER use bytes)
如有任何意见,我们将不胜感激.
Any comments would be appreciated.
推荐答案
查看 six,已经这样做了,并且加载了更多.它还具有帮助您在两个版本中执行二进制和 Unicode 的方法.但是,并非您需要执行的所有技术都可以通过这种方式完成,尤其是在您需要支持 Python 2.5 或更早版本的情况下.我试图在书中介绍其中的大部分,但我确定我错过了一些.
Check out six, that already does this, and loads more. It also has methods that helps you do binary and Unicode in both versions. Not all techniques you need to do can be done this way, though, especially if you need to support Python 2.5 or earlier. I tried to cover most of them in the book, but I'm sure I've missed out on some.
这篇关于python _2or3 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!