Are portable doctests for python 2 / python 3 poss

2019-04-21 11:19发布

问题:

def fib_r(n, memo={0: 0, 1: 1}):
    """recursive fibonacci numbers generation with memoisation

    >>> [fib_r(n) for n in range(10)]
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    >>> fib_r(100)
    354224848179261915075"""
    if n not in memo:
        memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]

The doctest above passes on python 3 but fails on 2.x like this:

**********************************************************************
File "euler.py", line 93, in __main__.fib
Failed example:
    fib_r(100)
Expected:
    354224848179261915075
Got:
    354224848179261915075L

This is just an example, I have seen this in several other situations (e.g. whether a unicode string has an u prefix or not). I was wondering if there is an option for doctest to ignore trivial differences between python 2 and 3 like this?

I am not looking for a workaround to modify the test itself so that it works despite the limitation. I just want to know if there is a flag or something to allow some lenience for compatibility with these minor things that have changed in python versions.

回答1:

doctests may provide different output between Python 2.x and 3.x, exactly for cases such as this, but of course other examples would be changed std-lib APIs.

The best bet, as someone has already noted in the comments on your question, is to find ways to produce doctest output that is consistent across 2.x and 3.x.

For your particular example, keep in mind that the definition of a Python long integer is architecture and interpreter dependent. A nice 128-bit Cray supercomputer would happily consider the result of fib(100) as a regular integer. So whether you get an L or not on the end of the value is more subtle than just 2.x vs 3.x -- although you are right that in 3.x L is now never displayed.