我可以想出两种方法来确保我可以在各种 Python 版本中使用单元测试库中的现代功能:
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
或
import sys
if sys.verson_info.major>=2 and sys.version_info.minor>=7:
from unittest import TestCase
else:
from unittest2 import TestCase
哪一个更Pythonic?
最佳答案
我会使用try
语句。这是一个经常使用的习语。
另外,您的 sys
版本对于 python3.3 来说是错误的:
>>> if sys.version_info.major>=2 and sys.version_info.minor>=7:
... from unittest import TestCase
... else:
... from unittest2 import TestCase
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ImportError: No module named 'unittest2'
虽然应该是:
>>> import sys
>>> major, minor = sys.version_info.major, sys.version_info.minor
>>> if (major >= 2 and minor >= 7) or (major >= 3 and minor >= 2):
... from unittest import TestCase
... else:
... from unittest2 import TestCase
...
>>>
这还表明 try
版本在 Python 版本中更加强大。
当我有一个用 C 编写的模块的“加速”版本时,我经常使用 try
变体,在文件末尾我放置了:
try:
from _accelerated import *
except ImportError:
pass
用加速的Python实现覆盖Python实现。
关于python - 在一系列 Python 版本中支持 unittest2 功能的最 Pythonic 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344380/