python - 将文档字符串中的预期结果指定为十六进制?

标签 python integer literals docstring doctest

有没有办法在 docstring 中指定预期的整数结果?用十六进制表示法?

def identity(val):
    """
    >>> identity(243)
    243
    >>> identity(243)
    0xf3
    """
    return val

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Doctest 不解释十六进制符号,导致失败:

**********************************************************************
File "hextest.py", line 5, in __main__.identity
Failed example:
    identity(243)
Expected:
    0xf3
Got:
    243
**********************************************************************
1 items had failures:
   1 of   2 in __main__.identity
***Test Failed*** 1 failures.

我知道我可以破解文档字符串:

def identity(val):
    """
    >>> hex(identity(243))
    '0xf3'
    """
    return val

但是让 doctest 理解似乎很自然 literal integers以 8 为基数,小数点后为 16。

最佳答案

当然,你可以自己写OutputChecker类来处理你想要的数字:

def identity(val):
    """
    >>> identity(243)
    0xf3
    >>> identity(243)
    243
    """

    return val


if __name__ == "__main__":
    import doctest

    OutputChecker = doctest.OutputChecker

    class HexOutputChecker(OutputChecker):

        def check_output(self, want, got, optionflags):

            if want.startswith('0x'):
                want_str = str(int(want, 16)) + '\n'
                return super().check_output(want_str, got, optionflags)
            else:
                return super().check_output(want, got, optionflags)

    doctest.OutputChecker = HexOutputChecker
    doctest.testmod(verbose=True)

关于python - 将文档字符串中的预期结果指定为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56392330/

相关文章:

Python 转换样式 : inside or out of function?

用于浮点和整数验证的 JavaScript

c++ - C++11中是否需要u8字符串文字

python - 为什么 [] 比 list() 快?

python - 如何在 scikit-learn 中找到所有稀疏数据回归量?

python - 如何正确使用 scipy 的 skew 和 kurtosis 函数?

sql - 如何比较sql server中的整数空值?

c++ - 空指针常量(nullptr)、空指针值和空成员指针值之间有什么区别?

Python:for 循环内 if 语句的 "breaking out"

python - 在python中将 float 转换为整数的最安全方法?