formatted docstrings

Cameron Simpson cs at cskk.id.au
Thu Apr 4 00:21:04 EDT 2019


On 04Apr2019 14:14, Cameron Simpson <cs at cskk.id.au> wrote:
>>Is it unreasonable to promote bare format strings as candidates for 
>>the docstring?

Yes it is. But being annoyed by this I've written this decorator:

    def fmtdoc(func):
      ''' Decorator to replace a function's docstring with that string
          formatted against the function's module's __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].
      '''
      func.__doc__ = func.__doc__.format(**sys.modules[func.__module__].__dict__)
      return func

I've stuffed it into my cs.deco PyPI package for reuse.

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

The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself.  Therefore all progress
depends on the unreasonable man.        - George Bernard Shaw


More information about the Python-list mailing list