I can think of two ways to ensure that I can use modern features from the unittest library across a wide range of Python versions:
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
or
import sys
if sys.verson_info.major>=2 and sys.version_info.minor>=7:
from unittest import TestCase
else:
from unittest2 import TestCase
Which one of these is more Pythonic?
For those of us who avoid the
from ... import ...
idiom, this imports the right unittest in a manner transparent to the rest of the code:I don't like the fact that in the second version we have to import another module (
sys
) so my preference is for the first version:EDIT:
It turns out that
pyflakes
andflake8
are not happy with the version above and will report a "redefinition of unused 'import' from line ... " error or "W402 'TestCase' imported but unused" error. They seem to prefer it to be written as follows:i'd use the
try
statement. It's an often used idiom. Also yoursys
version is wrong for python3.3:While it should be:
This shows also that the
try
version is more robust across python's versions.I often use the
try
variant when I have an "accelerated" version of the module written in C, at the end of the file I put a:to overwrite the python implementation with the accellerated one.