pythondocstring

Can a Python docstring be calculated (f-string or %-expression)?


Is it possible to have a Python docstring calculated? I have a lot of repetitive things in my docstrings, so I'd like to either use f-strings or a %-style format expression.

When I use an f-string at the place of a docstring

I do know how to process the docstrings after the import, but that doesn't work for object 'doc' strings which is recognized by sphinx but is not a real __doc__'s of the object.


Solution

  • Docstrings in Python must be regular string literals.

    This is pretty easy to test - the following program does not show the docstring:

    BAR = "Hello world!"
    
    def foo():
            f"""This is {BAR}"""
            pass
    
    assert foo.__doc__ is None
    help(foo)
    
    

    The Python syntax docs say that the docstring must be a "string literal", and the tail end of the f-string reference says they "cannot be used as docstrings".

    So unfortunately you must use the __doc__ attribute.

    However, you should be able to use a decorator to read the __doc__ attribute and replace it with whatever you want.