doctests compatibility for python 2 & python 3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jan 17 06:41:24 EST 2014


On Fri, 17 Jan 2014 11:16:17 +0000, Robin Becker wrote:

> I have some problems making some doctests for python2 code compatible
> with python3. The problem is that as part of our approach we are
> converting the code to use unicode internally. So we allow eihter byte
> strings or unicode in inputs, but we are trying to convert to unicode
> outputs.

Alas, I think you've run into one of the weaknesses of doctest. Don't get 
me wrong, I am a huge fan of doctest, but it is hard to write polyglot 
string tests with it, as you have discovered.

However, you may be able to get 95% of the way by using print.

def func(a):
    """
    >>> print(func(u'aaa'))
    aaa
    """
    return a

ought to behave identically in both Python 2 and Python 3.3, provided you 
only print one object at a time. This ought to work with both ASCII and 
non-ASCII (at least in the BMP).



-- 
Steven



More information about the Python-list mailing list