Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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.

like image 752
Wouter van Ooijen Avatar asked Sep 03 '25 17:09

Wouter van Ooijen


1 Answers

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.

like image 65
Colonel Thirty Two Avatar answered Sep 07 '25 07:09

Colonel Thirty Two