How to comply to PEP 257 docstrings when using Python's optparse module?

五迷三道 提交于 2019-12-03 08:08:37

Choice 1: Copy and paste. Not DRY, but workable.

Choice 2: Parse your own docstring to strip out the description paragraph. It's always paragraph two, so you can split on '\n\n'.

usage, description= __doc__.split('\n\n')[:2]

Since optparse generates usage, you may not want to supply the usage sentence to it. Your version of the usage my be wrong. If you insist on providing a usage string to optparse, I'll leave it as an exercise for the reader to work out how to remove "Usage: " from the front of the usage string produced above.

I wrote a module docopt to do exactly what you want – write usage-message in docstring and stay DRY. It also allows to avoid writing tedious OptionParser code at all, since docopt is generating parser based on the usage-message.

Check it out: http://github.com/docopt/docopt

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship [<name>] move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate.py -h | --help
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

I think we have to be reasonable about this PEP's advice -- I would think it's fine to leave the module with __doc__ being the short description that summarizes long usage. But if you're perfectionist:

'''<tool name>

The full description and usage can be generated by optparse module.

Description: ...

'''

...

# Generate usage and options using optparse.
usage, options = ... 

# Modify the docstring on the fly.
docstring = __doc__.split('\n\n')
docstring[1:2] = [__license__, usage, options]
__doc__ = '\n\n'.join(docstring)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!