Python doctests: test for None

Question:

Using Python 2.7 I’m trying to test that the result of a particular function call is None

I would expect these tests to pass (excuse the rather silly example)

def six_or_none(val):
    """
    >>> six_or_none(6)
    6
    >>> six_or_none(4)
    None
    """
    if val == 6:
        return 6
    return None

However they yield the following result

Failed example:
    six_or_none(4)
Expected:
    None
Got nothing

What’s the correct way to test for None in doctests?

Asked By: robert_b_clarke

||

Answers:

The Python interpreter ignores None return values, so doctests do the same.

Test for is None instead:

>>> six_or_none(4) is None
True
Answered By: Martijn Pieters

Other option would be a direct check for None:

def six_or_none(val):
    """
    >>> six_or_none(6)
    6
    >>> six_or_none(4)
    """
    if val == 6:
        return 6
    return None
Answered By: alko

Another alternative if you want something that looks like you might expect in your docs is:

>>> print(six_or_none(4))
None
Answered By: Sam Martin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.