Is it possible to deliver different source distributions for different Python versions?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Apr 6 03:00:48 CEST 2015


On Mon, 6 Apr 2015 06:38 am, Dave Hein wrote:

> I would like to distribute a python package with different code for
> Python 2.* than for Python 3.*. (Mostly this is because of different
> unicode string handling).
> 
> There is nothing in to setuptools or PyPi that directly supports
> this scenario.
> 
> But perhaps there could be some script run at install time that moves
> the correct source code to the right location? In other works, if I
> included both source code versions in the distribution (in a src2 and
> a src3 subdirectory) then a function invoked at install time could
> detect the python version and copy the appropriate source code to the
> right location.
> 
> Is that at all possible? Is there some install time hook that lets me
> supply custom installation code?

I'm not aware of any standard solution to that, but I'm not a setuptools
expert. setup.py files are Python code, so you can put any code you like in
them. But, as far as I am concerned, having the installer pick and choose
what source files to include is not a good solution. Instead, you should
pick one of these two alternatives:


(1) Supply a separate package for 2.x and 3.x, each with their own
installer. The installer confirms that it is running under the correct
version of Python, and just installs.


(2) Or supply a single package with a single installer that works under both
2.x and 3.x. (This is my preference.)

One way of handling the second case is to only support 3.3 or better: that
way, you can still use u"..." for Unicode strings. Hardly anyone used 3.1
or 3.2, and 3.0 is no longer supported, so it is quite reasonable to insist
people upgrade to 3.3.

Another way to handle the second case is to use conditional imports:


# mymodule2
mystring = u"äπЖ☃"  # Also works in 3.3 or better.

# mymodule3
mystring = "äπЖ☃"


# main application
from __future__ import print_function
from future_builtins import *
if sys.version < '3':
    import mymodule2 as mymodule
else:
    import mymodule3 as mymodule
print(mymodule.mystring)



-- 
Steven




More information about the Python-list mailing list