python _2or3 module?

梦想的初衷 提交于 2019-12-12 09:53:08

问题


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 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.


回答1:


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.



来源:https://stackoverflow.com/questions/5520286/python-2or3-module

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