Skip to content Skip to sidebar Skip to footer

Can I Have An Ellipsis At The Beginning Of The Line In A Python Doctest?

Python doctests are cool. Let me start with a simple example: def foo(): ''' >>> foo() hello world ''' print 'hello world' Now let's assume some part is somewha

Solution 1:

Here's a quick and dirty hack for you:

deffoo():
    """
    >>> foo() # doctest: +ELLIPSIS
    [...] world
    """print"hello world"if __name__ == "__main__":
    import doctest

    OC = doctest.OutputChecker
    classAEOutputChecker(OC):
        defcheck_output(self, want, got, optionflags):
            from re import sub
            if optionflags & doctest.ELLIPSIS:
                want = sub(r'\[\.\.\.\]', '...', want)
            return OC.check_output(self, want, got, optionflags)

    doctest.OutputChecker = AEOutputChecker
    doctest.testmod()

This still understands the normal ( ... ) ellipsis, but it adds a new one ( [...] ) that doesn't raise the line start ambiguity.

It would be seriously hard for doctest to guess whether there is a line continuation pending or whether its a line start ellipsis - it can be done, in theory, if you subclass DocTestParser to do that work but it probably won't be fun.

In complex situations you should probably roll your own DocTestRunner that would use the new OutputChecker and use that instead of the normal testmod but this should do in simple scenarios.

Solution 2:

You can update the ELLIPSIS_MARKER for your test so that ... does not get confused with the line continuation dots:

deffoo():
    """
    >>> import doctest
    >>> doctest.ELLIPSIS_MARKER = '-ignore-'
    >>> foo()
    hello world
    >>> foo() # doctest: +ELLIPSIS
    -ignore- world
    """print"hello world"if __name__ == "__main__":
    import doctest
    doctest.testmod()

Disclaimer: the example above works when doctests are run as

$ py.test --doctest-modulefoo.py

or

$ python foo.py

However, for reasons I don't understand it does not work when running doctests via

$ python -m doctest foo.py

Solution 3:

Here is a somewhat simpler way to do this: Just print a dummy string before the line that begins with the unknown output.

Like this:

deffoo():
  """
  >>> print 'ignore'; foo() # doctest: +ELLIPSIS
  ignore... world
  """print"hello world"

Solution 4:

I ended up with this workaround.

deffoo():
    """
    >>> foo()  # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    <BLANKLINE>
    ... world
    """print("hello world")

It at least works without non-whitespace characters or other workarounds.

Solution 5:

If you simply remove the trailing space after the ellipsis, this should work.

deffoo():   
    """
    >>> foo()  # doctest: +ELLIPSIS   
    ...world
    """print"hello world"

Post a Comment for "Can I Have An Ellipsis At The Beginning Of The Line In A Python Doctest?"