导入特定于版本的python模块的最佳方法
哪种方法最适合在python中导入特定于版本的模块?我的用例是我正在编写将部署到python 2.3环境中并在几个月内升级到python 2.5的代码.这个:
Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:
if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
或这个
try:
from string import Template
except ImportError:
from our.compat.string import Template
我知道这两种情况都是正确的并且可以正常工作,但是哪一种情况更可取?
I know that either case is equally correct and works correctly but which one is preferable?
总是第二种方式-您永远不知道将安装哪些不同的Python安装.在特定情况下,Template
的重要性降低了,但是当您测试该功能而不是版本控制时,您总是会更健壮.
Always the second way - you never know what different Python installations will have installed. Template
is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.
这就是我使 Testoob 支持Python 2.2-2.6的方法:我尝试以不同的方式导入模块,直到它作品.这也与第三方库相关.
That's how I make Testoob support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries.
这是一个极端的情况-支持ElementTree出现的不同选项:
Here's an extreme case - supporting different options for ElementTree to appear:
try: import elementtree.ElementTree as ET
except ImportError:
try: import cElementTree as ET
except ImportError:
try: import lxml.etree as ET
except ImportError:
import xml.etree.ElementTree as ET # Python 2.5 and up