Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I define a class in a doctest?

I would like to use a doctest comment block to demonstrate the usage of a particular base class, but either this cannot be done with doctest or I am doing something wrong. Here is my simple demo code.

class MyClass(object):
    '''
    >>> m = MyClass()
    >>> print m.x
    1
    >>> class A(MyClass):
    >>>  def __init__(self):
    >>>    super(A,self).__init__()
    >>>
    >>> a = A()
    >>> print a.x
    1
    '''


    def __init__(self):
        self.x = 1


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

The code doesn't run. Here's the first error issued:

Failed example:
class A(MyClass):
Exception raised:
Traceback (most recent call last):
  File "C:\Python27\lib\doctest.py", line 1254, in __run
    compileflags, 1) in test.globs
  File "<doctest __main__.MyClass[2]>", line 1
    class A(MyClass):
                    ^
SyntaxError: unexpected EOF while parsing
like image 527
Sven Avatar asked Nov 22 '12 10:11

Sven


People also ask

How does doctest work in Python?

The Doctest Module finds patterns in the docstring that looks like interactive shell commands. The input and expected output are included in the docstring, then the doctest module uses this docstring for testing the processed output.

Is it possible to use doctest for classes?

The doctest module looks for any docstrings in a file and executes any embedded code in it, so yes it is possible to use doctest for classes. As for whether it is better to put the doctests in the class's docstring or the constructor, I think that depends on what exactly you are documenting.

What is an example of a doctest for a function?

The following is a mathematical example of a doctest for a function such as add (a, b) that adds two numbers together: In this example we have a line of explanation, and one example of the add () function with two integers for input values.

What is the difference between doctestparser and doctestrunner?

DocTestParser: Creates a DocTest object from a string (such as an object’s docstring). DocTestRunner: Executes the examples in a DocTest, and uses an OutputChecker to verify their output. OutputChecker: Compares the actual output from a doctest example with the expected output, and decides whether they match.


1 Answers

Try it out in the interpreter; it uses ... to show continuation lines. >>> is only for a new statement or expression, while a class in incomplete until you've had an empty ... continuation line:

    >>> class A(MyClass):
    ...     def __init__(self):
    ...         super(A, self).__init__()
    ...
like image 84
Martijn Pieters Avatar answered Oct 02 '22 12:10

Martijn Pieters