Search code examples
pythonunit-testingdoctest

How to have decorated function in a Python doctest?


How can I include a decorated function inside a Python doctest?

def decorator(func):
    def wrapper() -> None:
        func()

    return wrapper

def foo() -> None:
    """
    Stub.

    Examples:
        >>> @decorator
        >>> def stub(): ...
    """

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

Running the above with Python 3.12 throws a SyntaxError:

UNEXPECTED EXCEPTION: SyntaxError('invalid syntax', ('<doctest path.to.a[0]>', 1, 0, '@decorator\n', 1, 0))

Solution

  • Multi-line commands should use ... for continuation lines. So the proper way is to use ... instead of >>> on the second line:

    def foo() -> None:
        """
        Stub.
    
        Examples:
            >>> @decorator
            ... def stub(): ...
        """