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.)
No, you cannot set the docstring of a function from within the body of the function, not without executing code either outside of the function, or inside the function (which requires calling the function first).
The way python normally sets the docstring is to take the first line of the function suite (everything indented under the
def
line) and if that's a string literal, it removes that from the suite and makes that the docstring. Python then compiles the rest of the suite into the function code object, and creates a newfunction()
object by passing in the compiled code object and the docstring (among others).If you use an expression that happens to produce a string instead, then that 'trick' doesn't work; python will ignore that expression, leaving it as part of the function suite to compile. Because the function suite itself is compiled and not executed, you cannot 'reach out' and set the docstring to be used on the function object during compilation time.
The only way you can dynamically set a function's docstring is by referring to a function object directly and setting it's
__doc__
orfunc_doc
variable (the two are aliases). Sure, that can be done in the function suite, but that's rather pointless, the docstring will be wrong until you do so.Note that when you import a function from a module, you already get the docstring too:
There is no need to import the docstring separately.
You can modify the
__doc__
attribute of the function at runtime:You cannot. The rule is: A string literal as first statement is taken as docstring. If it's an expression, it is not a string literal, and hence ignored.
You can also explicitly assign to the docstring attribute afterwards if you really need this. I don't see why you'd need it though. Your reasons seem fishy to me:
functools.wraps
.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):