31

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.

4
  • 2
    Does this answer your question? How do I programmatically set the docstring? Commented Jan 26, 2022 at 12:39
  • No, that is basically what I do now because an f-string as docstring doesn't seem to work, at least not with sphinx, and it is not recognized by checker tools. But it does seem to be 'executed' by normal Python. Commented Jan 26, 2022 at 12:46
  • 1
    Please show what the problem was with what you've tried. Commented Jan 26, 2022 at 12:47
  • I rolled that back Commented Jan 27, 2022 at 19:00

3 Answers 3

31

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that is what I feared. Unfortunately, post-processing the __doc__ strings doesn't work for objects, which are important for me ;(
I guess I'll have to preprocess the whole file before passing it to sphinx.
How would you make it work on sphinx? Indeed it is not working with Sphinx.
9

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)

1 Comment

Do you know if this works for napoleon sphinx?
1

a bit annoying, but another option is to generate the python file with a templating engine like jinja2. you will need to additionally create the template for your file and the logic to render it, but you will end up with a "normal" python file in the end, with literal docstrings that are compatible with sphinx, etc. etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.