开发者

Supporting Multiple Python Versions In Your Code?

开发者 https://www.devze.com 2022-12-08 02:37 出处:网络
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)

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 th开发者_高级运维is 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?


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.


You can certainly do

try:
  import v26
except ImportError:
  import v25

Dive Into Python—Using Exceptions for Other Purposes


Multiple versions of Python are supported here. You can a) conditionally use the newer version, which takes a little work, or b) turn off the warnings, which should really be the default (and is on newer Pythons).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号