3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

1 Answers1

6

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". 
Neuron
  • 5,141
  • 5
  • 38
  • 59
Philipp
  • 745
  • 2
  • 7
  • 20
  • 2
    Be careful about doing `foo.__doc__ = foo.__doc__.format` as it will likely fail if the module gets imported multiple times. It's safer just to do `foo.__doc__ = "something".format` – byxor Oct 25 '19 at 11:27
  • 3
    @byxor It can't ever fail. The body of a module is only evaluated once per Python instance. No matter the number of modules that import it. – Dan D. Oct 25 '19 at 11:37
  • 2
    @DanD. Excellent. In that case, go ahead. I just checked this and it's true. – byxor Oct 25 '19 at 11:52
  • Unfortunately, this doesn't seem to work with f-strings. They're not detected as docstrings belonging to the method. – Zoltán Aug 24 '22 at 14:09