Is it ok that python has 2 modules for option parsing, 3-4 xml packages, 3 HTTPServer modules, etc? This issue hit me when contemplating the deprecation of getopt as a part of the inclusion of argparse. Whenever I want to parse xml/html I get overwhelmed by the options in the std-lib. I remember myself annoyed and confused by getopt/optparse both showing me 2 different ways of doing something so similar. As a newcomer to python, I wanted python to show me the right way of doing things.
So following that line of thought, getopt is the ugly way of doing option parsing. It imitates an option parsing flow that came from the old C days (and thus unpythonic), making it very attractive for people familiar with getopt/xgetopt. So what’s more important: easy learning curve or enforcing best practices?
I wanted to see how ugly getopt code looks so using google code search I found a few real life usage examples.
getopt sample code, or check out the search results yourself:
- a very clean and complete usage of getopt, with a help string.
- a switch emulated with if’s
- a switch emulated with elif’s
- another switch the elif’s
- and another switch
optparse sample code:
- options are parsed and then used like a regular dict
- options are parsed and then used like a regular dict as part of a class
At first I thought the learning curve thing was important, but in the end, getopt is a very unpythonic module that I would rather not see any of my colleagues use at all, except for rare cases where an awful lot of flexibility is needed. For example, getopt could be an easy way to implement optparse, or a completely different alternative. For example pyopt uses getopt in such a way. So IMHO getopt should be in the std-lib, but the documentation should have a very big sign saying “use the awesome optparse/argparse, this is a very simple parser with barely any of the features you probably need”.