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 new function()
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__
or func_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:
>>> import itertools
>>> print itertools.groupby.__doc__
groupby(iterable[, keyfunc]) -> create an iterator which returns
(key, sub-iterator) grouped by each value of key(value).
There is no need to import the docstring separately.