2

I can put python doctests in the bodies of each function, which I sometimes like for small libraries, because they are in the same file as the function.

Or I can put them all together into a seperate file and execute the separate file, which is nice in case I do not want the doctest in between the functions. Sometimes I find the code is easier to work on if the docstrings are small.

Is there also a way to keep the python doctests in the same file, but put them all together at the end of the file?


EDIT: A solution, based on the accepted answer below:

def hello_world():
  return u'Hello World'


def hello(name):
  return u'Hello %s' % name


def doctest_container():
  """
  >>> hello_world()
  u'Hello World'

  >>> hello(u'Guido')
  u'Hello Guido'
  """
  pass


if __name__ == "__main__":
    import doctest
    doctest.testmod()

In fact it is simple, a dummy function is created as the last function that contains all the doctests in one docstring.

1
  • test() might be a better name than doctest_container(), you could move doctest.testmod() inside test(). I've updated the answer accordingly.
    – jfs
    Commented Mar 20, 2012 at 0:50

2 Answers 2

2

You can append the doctests to the docstring at the end of file like that:

def myfunc():
    """This is a docstring without a doctest
    """
    pass

# ... some other code here

# Add docstrings for doctest:
myfunc.__doc__ += """
>>> myfunc()
>>> repr(myfunc())
None
"""
1

doctest is to test that examples in your documentation are in sync with the implementation.

if there are many tests; unit tests written as code might be easier to maintain than doctest-based tests.

You could add a test function at the end of the module with desired doctests to avoid polluting docstrings of non-test code:

def test():
    """
    ..
    """
    import doctest
    doctest.testmod()

if __name__=="__main__": 
    test()  # if the module is called as a script then run tests
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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