Intrastellar Explorer
Intrastellar Explorer

Reputation: 2511

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))

Upvotes: 4

Views: 52

Answers (1)

m-sarabi
m-sarabi

Reputation: 2305

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(): ...
    """

Upvotes: 4

Related Questions