Repetitive content in docstrings
Question
What are good ways to deal with repetitive content in docstrings? I have many functions that take 'standard' arguments, which have to be explained in the docstring, but it would be nice to write the relevant parts of the docstring only once, as this would be much easier to maintain and update. I naively tried the following:
arg_a = "a: a very common argument"
def test(a):
'''
Arguments:
%s
''' % arg_a
pass
But this does not work, because when I do help(test)
I don't see the docstring. Is there a good way to do this?
Solution
As the other answers say, you need to change the __doc__
member of the function object. A good way to do this is to use a decorator that will perform the formatting on the docstring:
def fixdocstring(func):
func.__doc__ = func.__doc__.replace('<arg_a>', 'a: a very common argument')
#(This is just an example, other string formatting methods can be used as well.)
return func
@fixdocstring
def test(a):
'''
Arguments:
<arg_a>
''''
pass
OTHER TIPS
__doc__
is assignable on most user-defined types:
arg_a = "a: a very common argument"
def test(a):
pass
test.__doc__ = '''
Arguments:
%s
''' % arg_a
There is no obvious way to do this as far as I know (at least not without explicitely reassigning __doc__
as Ignacio suggests).
But I think this would be a terrible thing to do. Consider this:
What if I am navigating through your code and reading this docstring on the 300-th line of your file? You really want me to go search for the argument?