Search code examples
pythoninheritanceabstract-class

Force subclass to write a docstring


I have implemented an abstract class:

from abc import ABC, abstractmethod

class Study(ABC):

   """ Define the purpose of the study here """

   def __init__(self, value):
      self.value = value

   @abstractmethod
   def do_something(self):
      pass

I also implemented a subclass:

class PilotStudy(Study):

   def do_something(self):
      print('Pilot Study')

I would like to force the subclass to define a docstring below the class definition. Is there a way I can do this (such that an error is thrown for the subclass I defined above, since there is no docstring in that class)?


Solution

  • Use __init_subclass__. The __doc__ attribute of a class is set to the value of the class's docstring; if there is no doc string, the attribute is set to None.

    class Study(ABC):
    
       """ Define the purpose of the study here """
    
       def __init__(self, value):
          self.value = value
    
       @abstractmethod
       def do_something(self):
          pass
    
       def __init_subclass__(cls):
          if cls.__doc__ is None:
              raise AttributeError("No docstring")
    

    Then

    >>> class GoodStudy(Study):
    ...   "Do some stuff"
    ...
    >>> class BadStudy(Study):
    ...   pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<path>/abc.py", line 126, in __new__
        cls = super().__new__(mcls, name, bases, namespace, **kwargs)
      File "tmp.py", line 16, in __init_subclass__
        raise AttributeError("No docstring")
    AttributeError: No docstring