Search code examples
pythonpython-2.7docstring

Is it possible to include the value of a constant in a docstring?


I would like to do this:

FOO_CONSTANT = 1

def foo():
  """asdf """ + str(FOO_CONSTANT)

print(foo.__doc__)

Which should print:

asdf 1

But instead it prints

None

I can get the expected output with

FOO_CONSTANT = 1

def foo():
  """asdf """

foo.__doc__ += str(FOO_CONSTANT)
print(foo.__doc__)

but spreading the docstring across the code feels terrible.

Is it possible to include the value of a constant in a doc-string?

PS: I found this which is remotely related. The attempted approach there also does not produce a valid doc string, and note that it is about generating a dynamic docstring, while my FOO_CONSTANT is not expected to change. I just want to avoid repeating myself. The name FOO_CONSTANT has no meaning to the reader of the docstring, but the value does, and it appears in several docstrings where I do not want to repeat it.


Solution

  • I found this to be an interesting question and decided to look into it, but couldn't come up with an answer myself that does not spread the docstring, which you want to avoid.[1]

    But during looking into this issue I found these already answered questions that I hope should help you with a solution:

    1. How to put a variable into Python docstring
    2. python - how does one include a variable in the doc string?

    [1] Like something as this, where you at least can show in the docstring that there is a value missing.

    FOO_CONSTANT = 1
    
    def foo():
      """docstring with {0} or {1} replacements."""
    
    foo.__doc__ = foo.__doc__.format(1, 2)    
    print(foo.__doc__)   
    
    > "docstring with 1 or 2 replacements".