Docstrings – Handling Subclass Method Documentation

documentationinheritance

I have an abstract class structured somewhat like this:

class AbstractQuery(object, zip_code):
    def execute(self):
        """
        Retrieve information about a zip code
        The information returned will depend on the subclass
        """
        url, params = self._build_query(zip_code)
        response = requests.get(url, params=params)
        if self._is_valid(response):
            # etc.

    def _build_query(self, zip_code):
        """
        Returns a tuple (url, params) where
        url is the url of the API to query and
        params are the query params for the API call
        """
        raise NotImplementedError

    def _is_valid(self, response):
        """
        Returns True if response contains information necessary
        to continue processing
        """
        raise NotImplementedError

_build_query for example is always going to do the same thing, there's just going to be minor implementation differences. Do I just keep the docstring in the base class? Or copy/paste it down and violate DRY? What would a user or maintainer of these classes want to see?

Best Answer

From PEP 257:

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

If a class subclasses another class and its behavior is mostly inherited from that class, its docstring should mention this and summarize the differences. Use the verb "override" to indicate that a subclass method replaces a superclass method and does not call the superclass method; use the verb "extend" to indicate that a subclass method calls the superclass method (in addition to its own behavior).

So if you want to follow Python standards, use language indicating that the method is overriden in your subclass docstring.