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

Specify expected outcome in a docstring as hexadecimal?

有没有办法在 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 class 来处理您想要的数字:

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)