The doctest module seemed easy to implement so I decided to write a simpler version of it.


def _doublets(lst):
    for index, item in enumerate(lst[:-1]):
        yield item, lst[index+1]

def _test(tests):
    for prev, curr in _doublets(tests.splitlines()):
        if prev.strip().startswith('>>>'):
            code = prev.replace('>>>','').strip()
            if not eval(code) == eval(curr):
                raise AssertionError("{} should be {} but got {}".format(
                    code, eval(curr.strip()), eval(code)))

def doctest(func):

def testmod(module_name=None):
    with open(module_name or __file__) as f:


import my_doctest as doctest

def add(a, b):
    >>> add(1,3)
    >>> add(2,5) # I should study more Math ...
    return a + b


I don't think your parser is careful and general enough.

Where in testmod() does it say that it should consider only docstrings?

Also, what happens if the expected output is empty or more than one line? You also aren't handling code that spans multiple lines, with ... leaders.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.