Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python _2or3 module?

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.

like image 864
Garrett Berg Avatar asked Dec 06 '25 02:12

Garrett Berg


1 Answers

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.

like image 54
Lennart Regebro Avatar answered Dec 08 '25 15:12

Lennart Regebro