[Tutor] Using string formatting inside function docstrings

boB Stepp robertvstepp at gmail.com
Sat Apr 11 01:57:19 EDT 2020


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?  The only
possibility that occurs to me is rewriting an new version of the
source code containing the docstring to be formatted and then saved.
Would this be something someone would want to do during a package
installation perhaps feeding in appropriate environment parameters?

The author says that this cannot be done with f-string formatting, but
this suggested it might be possible with the other formatting
techniques.  So I started playing around with printf-style formatting
and by trying to be too clever got into some trouble.

This runs:

def fmt(*args):
    """Prints arguments of %s.""" % args[0]
    for i, arg in enumerate(args):
        print("arg #%s = %s " % (i, arg), end="")
    print()


fmt("Robert", "V.", "Stepp")

Giving:

bob at Dream-Machine1:~/Projects/Tutor_Help$ python3 s*
arg #0 = Robert arg #1 = V. arg #2 = Stepp

But my original idea of using this for the docstring:

"""Prints arguments of %s.""" % args

Throws an exception:

bob at Dream-Machine1:~/Projects/Tutor_Help$ python3 s*
Traceback (most recent call last):
  File "str_fmt.py", line 11, in <module>
    fmt("Robert", "V.", "Stepp")
  File "str_fmt.py", line 5, in fmt
    """Prints arguments of %s.""" % args
TypeError: not all arguments converted during string formatting

I am not understanding why this is happening (yet).  An explanation please?

Anyway, the running code demonstrates that one can use printf-style
formatting in docstrings...

-- 
boB


More information about the Tutor mailing list