prosseek
prosseek

Reputation: 190799

Executing Python doctest code

I have simple Python code that uses dockets

#!/usr/bin/python
# http://stackoverflow.com/questions/2708178/python-using-doctests-for-classes

class Test:
    def __init__(self, number):
        self._number=number

    def multiply_by_2(self):
        """
        >>> t.multiply_by_2()
        4
        """
        return self._number*2

if __name__ == "__main__":
    import doctest
    doctest.testmod(extraglobs={'t': Test(2)})

I can use it with python interpreter:

> python simple.py

However, when I execute the code from doctest module, I get this error:

> python -m doctest simple.py
**********************************************************************
File "simple.py", line 10, in simple.Test.multiply_by_2
Failed example:
    t.multiply_by_2()
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1289, in __run
        compileflags, 1) in test.globs
      File "<doctest simple.Test.multiply_by_2[0]>", line 1, in <module>
        t.multiply_by_2()
    NameError: name 't' is not defined
**********************************************************************
1 items had failures:
   1 of   1 in simple.Test.multiply_by_2
***Test Failed*** 1 failures.

Why is this difference? How to resolve this issue?

Upvotes: 2

Views: 1516

Answers (1)

mgilson
mgilson

Reputation: 309919

The difference is that when you execute via doctest, it is the __main__ module compared to executing directly where your script's if __name__ == '__main__' block will execute.

I don't know of a good solution other than to put all the information you need in the docstring itself:

def multiply_by_2(self):
    """
    >>> t = Test(2)
    >>> t.multiply_by_2()
    4
    """
    return self._number * 2

This will have the added benefit that users who are reading your docstrings will know what's going on ... They won't have to stumble upon your extraglobs keyword to figure out what t is and how it was initialized.

Upvotes: 5

Related Questions