Irfan Irfan - 1 year ago 59
Python Question

Multi version support for Python doctests

I am writing my doctests like this:

>>> some_function(a=1, b=2)
{u'id': u'123', u'name': u'abc'}

This works fine for Python version 2.5, 2.6 & 2.7 but fails for Python 3 with following error:

{u'id': u'123', u'name': u'abc'}
{'id': '123', 'name': 'abc'}

Problem is that if I write my doctests like this:

>>> some_function(a=1, b=2)
{'id': '123', 'name': 'abc'}

They will work only for Python3 and fail on Python2 version. My question is how do I make it cross version compatible?

Answer Source

I ran into the same problem with doctests in IPython. There's no neat solution, but I wrapped all of the u' prefixes in {}, i.e. {u}', and made a little function that would include or exclude them as appropriate.

You can see the u_format() function and a doctest using it.

But that's rather messy, so I've moved many tests away from doctests.

Alternatively, you can test it like this:

>>> some_function(a=1, b=2) == {'id': '123', 'name': 'abc'}

If you need some unicode strings in the keys, you can use u'abþ', and use distribute to run 2to3 on the doctests. But that only works on input code, not output reprs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download