Today I tried using pyPdf 1.12 in a script I was writing that targets Python 2.6. When running my script, and even importing pyPdf, I get complaints about deprecated functionality (md5->hashsum, sets). I’d like to contribute a patch to make this work cleanly in 2.6, but I imagine the author does not want to break compatibility for older versions (2.5 and earlier).
Searching Google and Stack Overflow have so far turned up nothing. I feel like I have seen try/except blocks around import statements before that accomplish something similar, but can’t find any examples. Is there a generally accepted best practice for supporting multiple Python versions?
There are two ways to do this:
(1) Just like you described: Try something and work around the exception for old versions. For example, you could try to import the
jsonmodule and import a userland implementation if this fails:This is an example from Django (they use this technique often):
If the iterator
reversedis available, they use it. Otherwise, they import their own implementation from theutilspackage.(2) Explicitely compare the version of the Python interpreter:
sys.version_infois a tuple that can easily be compared with similar version tuples.