Why use argparse rather than optparse?
I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to getopt
and optparse
we now have argparse
.
Why has yet another command-line parsing module been created? Why should I use it instead of optparse
? Are there new features that I should know about?
Solution 1:
As of python 2.7
, optparse
is deprecated, and will hopefully go away in the future.
argparse
is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):
- handling positional arguments
- supporting sub-commands
- allowing alternative option prefixes like
+
and/
- handling zero-or-more and one-or-more style arguments
- producing more informative usage messages
- providing a much simpler interface for custom types and actions
More information is also in PEP 389, which is the vehicle by which argparse
made it into the standard library.
Solution 2:
Why should I use it instead of optparse? Are their new features I should know about?
@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:
Why has yet another command-line parsing module been created?
That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?
Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email
package vs the myriad old ways to deal with similar issues isn't too far away either;-).
You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.
(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).