string interpolation in doc strings...

Skip Montanaro skip at mojam.com
Fri Dec 10 01:41:05 EST 1999


Getting a bit far afield from the original request, so I've trimmed the cc's
and references and changed the subject.

Barry wrote:

    Barry> def usage(code, msg=''):
    Barry>     print __doc__ % globals()
    Barry>     if msg: print msg
    Barry>     sys.exit(code)

    Barry> Then you put all the script's --help text in the module
    Barry> docstring, with a few %(thingie)s sprinkled around it.  Works
    Barry> really well!

I imagine some of the active particpants in the doc sig will have some
opinions about the use of format strings embedded in doc strings.  It's not
immediately obvious to me that it's good docstring stewardship.  For
example, in my PYTHONSTARTUP file I define the simple function:

    def help(x):
	try:
	    print x.__doc__
	except AttributeError:
	    print "no docstring available"

so I can type stuff like

    import string
    help(string.find)

at the interpreter prompt.

If string interpolation in doc strings becomes common practice, this simple
approach becomes less useful because I don't know just what context to
expect such strings to be evaluated.  I could modify my help function to try
and locate a dict to tack onto the print:

    from types import *
    def help(x):
	try:
	    if type(x) == ModuleType:
		print x.__doc__ % x.__dict__
	    else:
		print x.__doc__
	except AttributeError:
	    print "no docstring available"

but that seems like a very kludgy hack (that is, not at all general).

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list