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
Obviously开发者_Go百科 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.
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.
精彩评论