Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supporting Multiple Python Versions In Your Code?

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?

like image 244
technomalogical Avatar asked Oct 07 '09 15:10

technomalogical


2 Answers

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.

like image 180
Ferdinand Beyer Avatar answered Oct 25 '22 03:10

Ferdinand Beyer


You can certainly do

try:
  import v26
except ImportError:
  import v25

Dive Into Python—Using Exceptions for Other Purposes

like image 38
foosion Avatar answered Oct 25 '22 04:10

foosion