Fixing Python's DeprecationWarning sha

I thought I fixed this few days ago, but apparently I totally forgot to run the tests.

First time I have to go around a DeprecationWarning, and I thought it was cool to share. Maybe I’m totally doing it incorrectly, but at least I used a lambda! Whee!..

/mysql/connector/protocol.py:21: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
try:
    from hashlib import sha1
except:
    import sha
    sha1 = lambda s: sha.new(s)

print sha1('geert').digest()

Update 2009-10-01: I’ve changed the above code yet again to make it simpler and more conform to PEP 8 which says to use ImportError exception (thanks to Marius for this tip!):

try:
    from hashlib import sha1
except ImportError:
    from sha import new as sha1

Comments

Marius Gedminas
I suggest 'except ImportError' -- you wouldn't want to trap and ignore things like KeyboardInterrupt, if the user happens to press ^C exactly at the wrong moment, now would you?

I have, in fact, triggered funny errors from Ubuntu's command-not-found by pressing ^C very quickly after realizing I misspelt the command name.

If you don't feel very attached to the lambda, you can shorten the fallback part to 'from sha import new as sha1'. Just a stylistic suggestion; what you have will work fine too.
Geert JM Vanderkelen
@Marius

The ImportError-exception tip, I'm adding that. I see it's also in PEP8 (which I have to follow more..).

I'll also revert to the import you suggest. I didn't think of 'renaming' the new() method.

Thanks!
Marius Gedminas
Actually, the sha module has two names for the same class: 'sha' and 'new':

>>> import sha
>>> sha.new is sha.sha
True

So perhaps

from sha import sha as sha1

would look prettier, and more similar to 'from hashlib import sha1'.