I would like to set the func_doc (as an expression) within def.
def f():
'''My function help''' #Set the docstring
def g():
"My function " + "help" # An expression, so not read as a docstring
# can I put something here to set the docstring as an expression?
g.func_doc # is None
g.func_doc = "My function " + "help" # This works
Is this possible?
(two reasons I can think for doing this: importing a function from a module (and you want to import the docstring too) and using a lexer.)
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.
It can be used like this:
Or you can execute it directly, to modify an existing function (perhaps imported from another module):