[Tutor] Using string formatting inside function docstrings

Cameron Simpson cs at cskk.id.au
Sun Apr 12 19:59:27 EDT 2020


On 11Apr2020 00:57, boB Stepp <robertvstepp at gmail.com> wrote:
>I was looking at an online article, "Python 101 – Working with
>Strings", at https://www.blog.pythonlibrary.org/2020/04/07/python-101-working-with-strings/
> In the section, "Formatting Strings with f-strings", the author made
>a comment that intrigued me:
>
>"The expressions that are contained inside of f-strings are evaluated
>at runtime. This makes it impossible to use an f-string as a docstring
>to a function, method or class if it contains an expression. The
>reason being that docstrings are defined at function definition time."
>
>The intriguing part was the idea of using string formatting inside a
>function, method or class docstring.  Why would one want to do this?
>Can anyone give an interesting and practical example?

I do this.

My primary case is to document both the name of a module constant and 
its value so that help(thing) recites both. I do this often nough that I 
have a @fmtdoc decorator for this purpose. You can fetch my "cs.deco" 
module from PyPI to obtain this:

    https://pypi.org/project/cs.deco/

The documentation of @fmtdoc is about halfway down:

    Decorator to replace a function's docstring with that string formatted
    against the function's module __dict__.

    This supports simple formatted docstrings:

    ENVVAR_NAME = 'FUNC_DEFAULT'

    @fmtdoc
    def func():
        """Do something with os.environ[{ENVVAR_NAME}]."""
        print(os.environ[ENVVAR_NAME])

    This gives func this docstring:

        Do something with os.environ[FUNC_DEFAULT].

    Warning: this decorator is intended for wiring "constants" into 
    docstrings, not for dynamic values. Use for other types of values 
    should be considered with trepidation.

Note that warning.

Anyway, I find this quite handy.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list