[Tutor] Python 2 & 3 and unittest
Albert-Jan Roskam
fomcl at yahoo.com
Wed Sep 4 15:30:12 CEST 2013
Hi,
I am trying to make my app work in Python 2.7 and Python 3.3 (one codebase) and I might later also try to make it work on Python 2.6 and Python 3.2 (if I am not too fed up with it ;-). I was very happy to notice that the 'b' prefix for bytes objects is also supported for byte strings in Python 2.7. Likewise, I just found out that the "u" has been re-introduced in Python 3.3 (I believe this is the first Python 3 version where this re-appears).
I am now cursing myself for having used doctest for my tests. So I am planning to rewrite everything in unittest.
Is the try-except block below the best way to make this test work in Python 2.6 through 3.3?
import unitttest
import blah # my package
class test_blah(unittest.TestCase):
def test_someTest(self):
try:
expected = [u"lalala", 1] # Python 2.6>= & Python 3.3>=
except SyntaxError:
expected = ["lalala", 1] # Python 3.0, 3.1, 3.2
got = blah.yadiyadiyadi()
self.assertEqual(expected, got)
if __name__ == "__main__":
unittest.main()
Another, though related question. We have Python 2.7 in the office and eventually we will move to some Python3 version. The code does not generally need to remain Python2 compatible. What is the best strategy:
[a] write forward compatible code when using Python 2.7. (using a 'b' prefix for byte strings, parentheses for the print *statement*, sys.exc_info()[1] for error messages, etc.).
[b] totally rely on 2to3 script and don't make the Python2 code less reabable and less idiomatic before the upgrade.
Regards,
Albert-Jan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Tutor
mailing list