我希望我的代码在Python 2和3中工作。我使用医生和
from __future__ import unicode_literals
是否有我可以设置的标志/一个插件,它忽略了Python 2具有Unicode字符串的u
前缀?
示例
在Python 3中起作用的一个测试,但在Python 2中失败:
Expected:
'Me \& you.'
Got:
u'Me \& you.'
最小示例
from __future__ import unicode_literals
def foo():
"""
Returns
-------
unicode - for Python 2 and Python 3
Examples
--------
>>> foo()
'bar'
"""
return 'bar'
if __name__ == '__main__':
import doctest
doctest.testmod()
如果您直接使用医生,则可以根据Dirkjan Ochtman的博客文章单源Python 2/3 Doctests覆盖Outputchecker:
class Py23DocChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
if sys.version_info[0] > 2:
want = re.sub("u'(.*?)'", "'\1'", want)
want = re.sub('u"(.*?)"', '"\1"', want)
return doctest.OutputChecker.check_output(self, want, got, optionflags)
doctest.DocTestSuite(mod, checker=Py23DocChecker())
如果您使用的是py.test,则可以在pytest.ini中指定 doctest_optionflags = ALLOW_UNICODE
。请参阅https://docs.pytest.org/en/latest/doctest.html