Search code examples
pythonabstract-classdoctesterror-suppression

Suppressing doctest in abstract or Protocol classes


I am looking to use doctest formatted examples for an abstract (ABC) or Protocol class without having doctest fail because the methods of the class are not implemented.

The docstring and example is supposed to reflect the general use case of multiple implementations of the abstract class and I would like to keep the doctest format for consistency.

Any idea for suppressing the doctest for a single docstring or for all abstract or Protocol classes is appreciated. I know I could also write is as a Sphinx code block but it wouldn't be as human readable in the code in my opinion.

Example:

from abc import ABC, abstractmethod

class MyABC(ABC):
    """My docstring.

    Here is a recommended use case for this item:

    Examples:
        >>> a = MyABC()
        >>> a.do_something()
        'some expected behaviour'
    """
    
    @abstractmethod
    def do_something(self):
        pass


class MyClass(MyABC):
    def do_something(self):
        return 'some expected behaviour'

N.B. I am aware that this ticket is kinda duplicate but I don't think the example was pertinent, nor has it been answered.


Solution

  • Your doc test has to do the same thing a user would be expected to do: define a subclass that implements do_something and instantiate that class.

    class MyABC(ABC):
        """My docstring.
    
        Here is a recommended use case for this item:
    
        Examples:
            >>> class Foo(MyABC):
            ...   def do_something(self):
            ...       return 'some expected behaviour'
            ...
            >>> a = Foo()
            >>> a.do_something()
            'some expected behaviour'
        """
    
        @abstractmethod
        def do_something(self):
            pass