[docs] Suggested easy improvement to Python "getopt" documentation.

Karl Fogel kfogel at red-bean.com
Fri Apr 21 20:17:15 EDT 2017


This suggestion is for both https://docs.python.org/2/library/getopt.html and https://docs.python.org/3/library/getopt.html.

In the example that follows this text:

  "In a script, typical usage is something like this:"

I'd like to suggest that commas be added to emphasize list syntax, as in this patch:

  --- a	2017-04-21 19:04:28.596468414 -0500
  +++ b	2017-04-21 19:04:37.300326415 -0500
  @@ -13,10 +13,10 @@
       for o, a in opts:
           if o == "-v":
               verbose = True
  -        elif o in ("-h", "--help"):
  +        elif o in ("-h", "--help",):
               usage()
               sys.exit()
  -        elif o in ("-o", "--output"):
  +        elif o in ("-o", "--output",):
               output = a
           else:
               assert False, "unhandled option"

Adding the commas would prevent the following bad scenario:

If someone copies the example code and modifies it heavily, they could easily end up with something like this:

  for o, a in opts:
      if o in ("-h", "-?", "--help", "--usage"):
          usage()
          sys.exit(0)
      elif o in ("--show-columns"):
          show_columns = True
      elif o in ("-c", "--config"):
          config = parse_config_file(a)
      else:
          assert False, "unhandled option"

You can see the problem with the first 'elif' case.  When the value of 'o' is "-c", it will improperly match, because

  o in ("--show-columns")

would be improperly True, whereas

  o in ("--show-columns",)

would have been properly False.

Adding the commas would emphasize that these are lists, and make this kind of copy-paste-massage bug less likely to happen.

(By the way, I tried to report this by filing a bug in http://bugs.python.org/, but some glitch in the registration process won't let me register "kfogel" now.  I'm already deep enough in yak shaving that I don't want to debug that problem at the moment, but if you can reset/clear that account, I'd be happy to simply re-try the registration process.)

Best regards,
-Karl Fogel


More information about the docs mailing list