哪些方法使得用于导入在python的模块是特定于版本的最有意义?我使用的情况是,我正在写将被部署到一个Python 2.3环境,并在几个月后升级到Python 2.5的代码。这样:

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

我知道这两种情况下是同样正确和正常工作但哪一个是优选的?

有帮助吗?

解决方案

始终第二种方式 - 你永远不知道什么不同的Python安装将已经安装。 Template是真正重要的事情少了具体情况,但是当你测试的能力,而不是你总是更强劲的版本。

这就是我做的 Testoob 支持的Python 2.2 - 2.6:我尝试导入以不同方式模块,直至其作品。这也是有关的第三方库。

下面是一个极端的情况下 - 支持不同选项ElementTree的出现:

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

其他提示

我可能会认为,第二个将是优选的。有时候,你可以从蟒蛇的新版本上安装的模块为一老一。例如,附带的wsgiref与Python 2.5,但它是不完全罕见它被安装到旧版本(我认为它会与Python 2.3起来工作)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top