Python 2 和 3 中带有 numpy 数组的文档测试

doctests with numpy arrays in Python 2 and 3

我正在使用 Python doctests 来处理应该与 Python 2 和 Python 3 一起使用的代码。除了我使用包含字符串的 numpy 数组外,其他一切正常.对于Python 3,以下是正确的:

>>> np.array(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])   # doctest: +NORMALIZE_WHITESPACE
array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'],
      dtype='<U3')

使用 Python 2,预期结果为:

array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'],
      dtype='|S3')

注意 <U3|S3 的区别。

是否有任何简单的方法来调整我的代码以能够通过两个 Python 版本的测试?我想尽可能地进行租赁侵入性变更。由于 doctests 也针对用户(因此他们可以看到如何使用代码)我不希望太复杂或误导性的代码给他们正确用法的错误印象。

我不知道这对你来说是否可以接受,但差异仅在 __repr__:

中可见
>>> A = np.array(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])
>>> A
array(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
       'oct', 'nov', 'dec'], 
      dtype='|S3')

因此,如果您更改 doctests 以检查数组的打印输出,它应该是兼容的。

>>> print(A)
['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec']

这充其量只是一个 hacky 解决方法,但 doctests 非常有限并且不灵活 python 2 / python 3 兼容性。