17

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

  • importing the module invokes the processing
  • but when I check the __doc__ of such a function it is empty
  • sphinx barfs when the docstring is an f-string

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.

2 Answers2

13

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.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
2

We had the same problem, and what we might end up doing is this:

BAR = "Hello world!"

class A():
    __doc__ = f"""This is {BAR}"""
    pass

help(A)

chaos.ct
  • 1,001
  • 1
  • 7
  • 18