I have a collection of functions with (mostly) shared parameters but different processes. I'd like to use a decorator to add the description for each parameter to a function's headline-level docstring.
I've tried to mimic the structure found in this answer by incorporating a nested function within appender
but failed. I've also tried functools.partial
but something is slightly off.
My attempt:
def appender(func, *args):
"""Appends additional parameter descriptions to func's __doc__."""
def _doc(func):
params = ''.join([defaultdocs[arg] for arg in args])
func.__doc__ += '\n' + params
return func
return _doc
defaultdocs = {
'a' :
"""
a : int, default 0
the first parameter
""",
'b' :
"""
b : int, default 1
the second parameter
"""
}
@appender('a')
def f(a):
"""Title-level docstring."""
return a
@appender('a', 'b')
def g(a, b):
"""Title-level docstring."""
return a + b
This fails, and it fails I believe because the first arg passed to appender
is interpreted as func
. So when I view the resulting docstring for g
I get:
print(g.__doc__)
Title-level docstring.
b : int, default 1
the second parameter
because, again, 'a'
is interpreted to be 'func'
when I want it to be the first element of *args
. How can I correct this?
Desired result:
print(g.__doc__)
Title-level docstring.
a : int, default 0
the first parameter
b : int, default 1
the second parameter