37

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?

robert_b_clarke
  • 1,463
  • 10
  • 13

3 Answers3

66

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

Test for is None instead:

>>> six_or_none(4) is None
True
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Martijn, do you know the motivations for ignoring None? –  Nov 18 '13 at 12:24
  • 1
    @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. – Martijn Pieters Nov 18 '13 at 12:25
  • @EdgarAroutiounian: You'd never be done reading past all the `None` outputs if you did echo those. – Martijn Pieters Nov 18 '13 at 12:26
  • 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? – benjimin Aug 18 '20 at 03:40
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
alko
  • 46,136
  • 12
  • 94
  • 102
1

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

>>> print(six_or_none(4))
None
Sam Martin
  • 1,238
  • 10
  • 19