Jon
Jon

Reputation: 12874

Python: How can I create a Python project compatible to Python 2 and Python 3?

I want to create a package which should be compatible to Python 2.7 and Python 3.3. The logic should exist only once.

How do you normally represent the programming logic - in Python 2.7 or Python 3.3? Or do you choose a different way?

EDIT: How this issue is handled in the core?

Upvotes: 0

Views: 317

Answers (2)

Lennart Regebro
Lennart Regebro

Reputation: 172229

You do it by quite simply only using those bits of the language that is the same, and by having conditions or exception handling during other parts.

This is harder or easier depending on what your software do, and what versions of Python you need to support. By supporting just Python 2.6, 2.7 and 3.3 it becomes relatively simple.

Exactly how you do it is not answerable in a question on SO, because there is a lot to it.

I recommend you check out this book: http://python3porting.com/ , especially the chapter "Supporting Python 2 and 3 without 2to3 conversion" and the Appendices, that has loads of examples of how to solve most incompatibilities.

The six library may also be useful.

Upvotes: 2

user707650
user707650

Reputation:

I tend to use a number of __future__ imports (which are, presumably, safely ignored in Python 3), and the occasionaly try except for some import statements. In addition, I define a stringtype for basestring / str compatibility. Just depending on what I need per module.

For example:

from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function
try:
    import ConfigParser as cfgparser
except ImportError:
    import configparser as cfgparser
try:
    stringtype = basestring
except NameError:
    stringtype = str

I think the six package already does this, so that may be another good option.

Upvotes: 2

Related Questions