doctests compatibility for python 2 & python 3

Robin Becker robin at reportlab.com
Fri Jan 17 07:12:35 EST 2014


On 17/01/2014 11:41, Steven D'Aprano wrote:
> def func(a):
>      """
>      >>> print(func(u'aaa'))
>      aaa
>      """
>      return a
I think this approach seems to work if I turn the docstring into unicode

def func(a):
	u"""
	>>> print(func(u'aaa\u020b'))
	aaa\u020b
	"""
	return a
def _doctest():
	import doctest
	doctest.testmod()

if __name__ == "__main__":
	_doctest()

If I leave the u off the docstring it goes wrong in python 2.7. I also tried to 
put an encoding onto the file and use the actual utf8 characters ie

# -*- coding: utf-8 -*-
def func(a):
     """
     >>> print(func(u'aaa\u020b'))
     aaaȋ
     """
     return a
def _doctest():
     import doctest
     doctest.testmod()

and that works in python3, but fails in python 2 with this
> (py27) C:\code\hg-repos>python tdt1.py
> C:\python\Lib\doctest.py:1531: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - in
> terpreting them as being unequal
>   if got == want:
> C:\python\Lib\doctest.py:1551: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - in
> terpreting them as being unequal
>   if got == want:
> **********************************************************************
> File "tdt1.py", line 4, in __main__.func
> Failed example:
>     print(func(u'aaa\u020b'))
> Expected:
>     aaaȋ
> Got:
>     aaaȋ
> **********************************************************************
> 1 items had failures:
>    1 of   1 in __main__.func
> ***Test Failed*** 1 failures.


--
Robin Becker




More information about the Python-list mailing list