I would like to set the func_doc
(as an expression) within def
.
def f():
\'\'\'My function help\'\'\' #Set the
You can't do that, since only a string literal is recognized as a docstring. But you can use a decorator to set or modify a function's docstring. (You can also modify __doc__
explicitly in executable code, but a decorator is much cleaner since it is logically part of the declaration).
This can be useful, for example, if you have several functions that should contain the same text as (part of) their docstring. Here's a little decorator that appends its argument (literal or a variable) to a function's declared docstring.
def docstring(docstr, sep="\n"):
"""
Decorator: Append to a function's docstring.
"""
def _decorator(func):
if func.__doc__ == None:
func.__doc__ = docstr
else:
func.__doc__ = sep.join([func.__doc__, docstr])
return func
return _decorator
It can be used like this:
@docstring("copyright by nobody")
def testme():
"This function does nothing"
pass
Or you can execute it directly, to modify an existing function (perhaps imported from another module):
from re import sub
docstring("Copyright unknown")(sub)