Python doctests: test for None
Asked Answered
L

3

39

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?

Lobell answered 18/11, 2013 at 12:12 Comment(0)
I
69

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

Test for is None instead:

>>> six_or_none(4) is None
True
Individually answered 18/11, 2013 at 12:13 Comment(5)
Martijn, do you know the motivations for ignoring None?Rudyrudyard
@EdgarAroutiounian: None is the default "I have to return something but if I were allowed not to return anything I'd do so" return value.Individually
@EdgarAroutiounian: You'd never be done reading past all the None outputs if you did echo those.Individually
I wonder why doctest doesn't just treat as empty an expected output solely consisting of the line "None"; perhaps the principle is to avoid surprising a user who manually checks the documented example in an interactive interpreter?Scepter
@Scepter "... manually checks the documented example in an interactive interpreter" - Exactly. Doctests are supposed to look as much like an interactive session as possible.Begonia
P
9

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
Prevalent answered 3/12, 2013 at 20:27 Comment(0)
I
1

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

>>> print(six_or_none(4))
None
Interchangeable answered 25/12, 2020 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.