Reputation: 567
I'm working on modifying a library that currently only works under Python 2.6/2.7 to make it work under 3.x.
Is the following code segment the proper way to do it? I'm specifically asking about lines 5-13 & 29-33:
# Example file
# Deina
###############################################################################
import sys
ver = sys.version_info[0]
if ver == 2:
import Py2lib-1 ## wrong libs for Python 3
import Py2lib-2
else:
import Py3lib-1 ## wrong libs for Python 2
import Py3lib-2
class Part(object):
def __init__(self, parameters, payload, content_type=None):
self.content_type = content_type
self.parameters = parameters
self.payload = payload
###############################################################################
# other lines of code go here that work in either version
###############################################################################
def render(self):
'''Renders this part -> List of Strings'''
parameters = ['%s="%s"' % (k, v)
if ver == 2:
for k, v in self.parameters.iteritems()] ## Python 2.7
else:
for k, v in self.parameters.items()] ## Python 3
###############################################################################
# other lines of code go here that work in either version
###############################################################################
return lines
Upvotes: 1
Views: 68
Reputation: 9726
First, yes, it is certainly possible, and often wise (also convenient both for developers and users). It usually depends on how much you are relying on that part of standard library and syntax that changed between 2 and 3. I have my own project that runs both with 2 and 3, and I'm quite happy with it.
Concerning your code, I would create "compatibility functions" somewhere at the start of the module, or even in their own module instead of conditional imports (you do not really need the whole module, do you?) and version checks throughout the code, which are hard to maintain.
There is a very good blog post on the architecture of such projects by Armin Ronacher, which addresses many arising issues.
Upvotes: 2