ARTICLE AD BOX
In Python, a function is a first-class object, which is created when the compiler finds the function body: it then build the code object, containing the bytecodes, and creates a function object (of type FunctionType), by agregating some metadata, like name, file name, default arguments, and...the docstring: which must be a single string written as first expression in the function body.
No code inside the function is executed, or otherwise evaluated at compile time - so, either calling a string's .format method, or evaluating a f-string.
So, the answer is pretty much that the docstring is statically fetched from the function body, and assigned to the __doc__ attribute - and never the result of evaluating an expression.
You will find that even with the use of decorators, a pattern that allows one to customize almost everything about a function creation, doing this would be tricky: as it would require running just the string-formatting part of the function, and not the whole function. A decorator would otherwise make it simple to customize the docstring for the function - but running "partial code" from inside a function is not trivially doable (it probably would require going either through the function bytecode, or re-generating its AST from source to run just that expression).
BUT - you can place the desired doc-string outside the function body instead, as a parameter to the decorator instead (and then, all the decorator do is to assign that parameter as the docstring). That will work:
>>> def dyndoc(docstr): ... def deco(func): ... func.__doc__ = docstr ... return func ... return deco ... >>> answer = 42 >>> >>> @dyndoc(f"This return import data about the {answer}") ... def myfunc(question): ... return "we apologize for the inconvenience" ... >>> myfunc.__doc__ 'This return import data about the 42' >>>(side note, it is 2025, and .format calls are pretty much obsolete, except in a few places that require lazy evaluation - you probably should be concerned about using f-strings, not calling str.format)
