哈希库/md5。与Python 2.4的兼容性

发布于 2024-08-04 13:04:17 字数 356 浏览 2 评论 0原文

python 2.6 报告 md5 模块已过时,应使用 hashlib。如果我将 import md5 更改为 import hashlib 我将解决 python 2.5 和 python 2.6,但不能解决 python 2.4,因为它没有 hashlib 模块(导致 ImportError,我能抓住)。

现在,为了解决这个问题,我可以执行 try/catch,并定义一个 getMd5() 函数,以便根据 try 块的结果定义正确的函数。这个解决方案可以吗?

在更一般的情况下,您将如何解决这个问题,例如:您有两个具有相同目标但不同接口的不同库,并且您想使用一个,但如果第一个不是,则回退并使用另一个成立。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2024-08-11 13:04:17

一般来说,以下构造就可以了:

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

在您的特定情况下,也许:

try: 
   from hashlib import md5
except ImportError:
   from md5 import md5

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
妄想挽回 2024-08-11 13:04:17

在模块具有相同接口的情况下,就像它们在这里一样,您描述的解决方案很好。您还可以将导入隔离到其自己的模块中,如下所示:

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

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

在它们具有不同接口的情况下,您需要编写一个适配器来按照您指定的方式对齐接口。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文