views:

728

answers:

2

Hi all.

python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change import md5 to import hashlib I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).

Now, to fix it, I could do a try/catch, and define a getMd5() function so that a proper one gets defined according to the result of the try block. Is this solution ok?

How would you solve this issue in a more general case, like, for example: you have two different libraries with the same objective but different interface, and you want to use one, but fall back and use the other if the first one is not found.

+10  A: 

In general the following construct is just fine:

try:
    import module
except ImportError: 
    # Do something else.

In your particular case, perhaps:

try: 
   from hashlib import md5
except ImportError:
   from md5 import md5
Triptych
+1  A: 

In the case where the modules have the same interface, as they do here, the solution you described is fine. You could also isolate the import into its own module like this:

hash.py
----
try:
   import hashlib.md5 as md5mod
except ImportError:
   import md5 as md5mod

-----
prog.py
-----
from hash import md5mod
....

In the case where they have different interfaces you would need to write an adaptor to align the interfaces as you have specified.

jkp
Note that a naked `except` statement here is pretty dangerous, since it would hide errors in modules that are found but throw exceptions within the module's source.
Triptych
Thanks, I've qualified the statement now.
jkp