views:

108

answers:

2

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?

+4  A: 

You can certainly do

try:
  import v26
except ImportError:
  import v25

Dive Into Python—Using Exceptions for Other Purposes

foosion
+1, but here's a direct link to the relevant section: http://diveintopython.org/file_handling/index.html#d0e14344
technomalogical
+8  A: 

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 json module and import a userland implementation if this fails:

try:
    import json
except ImportError:
    import myutils.myjson as json

This is an example from Django (they use this technique often):

try:
    reversed
except NameError:
    from django.utils.itercompat import reversed     # Python 2.3 fallback

If the iterator reversed is available, they use it. Otherwise, they import their own implementation from the utils package.


(2) Explicitely compare the version of the Python interpreter:

import sys
if sys.version_info < (2, 6, 0):
    # Do stuff for old version...
else:
    # Do 2.6+ stuff

sys.version_info is a tuple that can easily be compared with similar version tuples.

Ferdinand Beyer