Search code examples
pythonpython-3.xstring-formattingdocstring

Using string formatting within class method docstrings


I have a class with several similar methods, each with long docstrings that are similar but vary with regards to several phrases/words. I'd like to build a docstring template and then apply string formatting to it. Below is a clumsy implementation where the __doc__s are defined after the class methods.

capture_doc = """
%(direc)s normal.

a %(sym)s b."""

class Cls():    
    def a(self):
        pass
    def b(self):
        pass
    a.__doc__ = capture_doc % {'direc' : 'below', 'sym' : '<'}     
    b.__doc__ = capture_doc % {'direc' : 'above', 'sym' : '>'}

c = Cls()    
print(c.a.__doc__)

below normal.

a < b.

Question: is there a Python docs- or PEP-prescribed way to do this? I'd like to keep things basic, I've seen use of an @Appender decorator but think that's a bit fancy for my needs.


Solution

  • You shouldn't do this. You seem to assume your docstring should only serve those who use your code and need help with how it works.

    Docstrings are supposed to provide some form of the documentation for the associated object for those reading your code, so this makes your docstring half its worth. I doubt any one would love to go through the trouble of having to format those strings (in their heads or using the interpreter) to figure out what your code does or how it works.

    From PEP 257:

    What is a Docstring?

    A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

    [Emphasis mine]

    With your implementation, one could pedantically argue you don't have docstrings albeit __doc__ attributes.