5

I have a function that starts like this:

def apply_weighting(self, weighting):
    """
    Available functions: {}
    """.format(weightings)

What I want is for the docstring to print the dictionary of available weighting functions. But when inspecting the function it states that there are no docstring available:

In [69]: d.apply_weighting?
Type:       instancemethod
String Form:<bound method DissectSpace.apply_weighting of <dissect.DissectSpace instance at 0x106b74dd0>>
File:       [...]/dissect.py
Definition: d.apply_weighting(self, weighting)
Docstring:  <no docstring>

How come? Is it not possible to format a docstring?

Jimmy C
  • 9,270
  • 11
  • 44
  • 64
  • 1
    if your docstring is so generic that you can use a formatstrnig on it ... is there any real advantage to having it? – Joran Beasley Feb 17 '14 at 20:30
  • @JoranBeasley The weightings contains a string -> function dictionary which contains all available weighting functions I can apply. By having them readily available in the docstring, looking up which ones to use is easy. – Jimmy C Feb 17 '14 at 20:35

1 Answers1

10

The Python interpreter looks for string literals only. Adding a .format() method call is not supported, not for the function definition syntax. It is the compiler that parses out the docstring, not the interpreter, and any variables like weightings are not available at that time; no code execution takes place at this time.

You can always update a docstring after the fact:

def apply_weighting(self, weighting):
    """
    Available functions: {}
    """

apply_weighting.__doc__ = apply_weighting.__doc__.format(weightings)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343