I’d like to make it as general as possible – e.g. handle as many versions as possible.
Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement.
Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic based on what (e.g. libraries) is available.
Suppose I have a script that will run under version 1.x, or 2.x, or 3.x only.
Or a script which requires a library A or a library B.
Thanks!
EDIT:
Now … when it comes to Python (unlike .Net) some libraries like SciPy, Google App Engine keep you glued to particular version. On Linux, Mac Os you can switch between different Python installs on command line. This is why I want to avoid confusion – I want to remember which script is for which version of Python and what libraries it needs. I would rather have it fail in a human-readable way.
If you want to maintain a codebase that works with Python 2 and 3, you wouldn’t try to make code that will run in both, which will be awkward and ugly and bugprone, you would write in Python 2 and useEdit: This was common wisdom in 2010, but turned out not to be the case. The thing to do is write a polyglot. 2to3 did not end up being all that useful2to3to convert. (You can also write in Python 3 and use3to2to convert, but I believe that tool is less mature.)2to3is not perfect, but making Python 2 code that can be converted by it makes tons more sense than making Python 2 code that will run in a Python 3 interpretter.Another option is Cython, a Python-like language that can be used to create C extension modules. Cython modules can be used with Python 2 and 3.
When you support multiple versions of Python, it is generally better to directly check for the capability you want rather than to check a version number. Checking version numbers directly is fragile and indirect.
For example, if I wanted code that would work with Python pre-2.5, I would say:
(note that this is prettymuch the only reason to catch
NameError). Similarly, library availability would be checked by catchingImportError. Edit: There is a tons of tooling for abstracting this away by now.If you want a script to remember what version it is from, like you say, don’t bother trying to support multiple versions at all. Put the proper version number binary in the shebang line and run the script based on that.