Packaging python libraries with version-specific (2/3) code
Question: I have a Python library written to work under both Python 2 and Python 3, with
all the version-specific code localized in one module that exists in two
variants, one source code file for Python 2 and one for Python 3. Each file
contains code that raises a SyntaxError if imported into the wrong Python
version.

When I package my library with distutils and install it, I always get a syntax
error report for one or the other file. Is there a way to get rid of this?
Ideally, I would like to tell distutils/setuptools to ignore the file that is
not for the currently running Python version.


Answer: distutils imports all modules to byte-compile them (i.e. create the pyc and
maybe pyo files) at build time and/or install time. There is no option
currently to have a module skipped. You could write your setup script so that
a different sdist is generated for Python 2 and Python 3 (so for example
somemodule2.py would not be included in the Python 3 sdist), but not all tools
work well with different sdists, including PyPI.

At the current time, I would try to make each module not raise a SyntaxError
when imported by either Python 2 or 3. Or I would follow Martijn’s advice and
write just one module, possibly using the six modules, if the end result is
not too messy (I’ve seen really horrible 2-and-3 code so I don’t like that
solution, but a big part of the community has chosen it because it works).

